How to notify users to rate app on playstore

This post is about how to notify users to rate the app on playstore. Play store policy suggests us if we are notifying users to perform some action in our app then we must also let users to cancel the operation if user doesn't want to perform that action. We must give option to perform an action or to cancel that action which'll depend on the users choice what they want to do. Like if we are notifying users to update the app or rate the app on play store with Yes(Now) then we must also give an option for No(Later, Not Now) etc. So, if user like to perform that action then they choose Yes(Now) or if then don't want then they can cancel it by choosing No(Not Now, Later) etc.

The code given below will notify users on a defined time depends upon you. Just attach the given code in your project and write the one live of code in onBackPressed method of Main_Activity.java:

new AppRate(this).setMinDaysUntilPrompt(0) .setMinLaunchesUntilPrompt(5) .setShowIfAppHasCrashed(false).init();


 

This app function uses the SharedPreference class to set the timing to display the popup for rating. Whole code is as given below :

 

import java.lang.Thread.UncaughtExceptionHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.text.format.DateUtils;
import android.util.Log;

public class AppRate implements android.content.DialogInterface.OnClickListener, OnCancelListener {

private static final String TAG = "AppRater";

private Activity hostActivity;
private OnClickListener clickListener;
private SharedPreferences preferences;

private long minLaunchesUntilPrompt = 0;
private long minDaysUntilPrompt = 0;

private boolean showIfHasCrashed = true;

Editor editor;

public AppRate(Activity hostActivity) {
this.hostActivity = hostActivity;
preferences = hostActivity.getSharedPreferences(PrefsContract.SHARED_PREFS_NAME, 0);
}

/**
* @param minLaunchesUntilPrompt The minimum number of times the user launches the application before showing the rate dialog.
* Default value is 0 times.
* @return This {@link AppRate} object to allow chaining.
*/
public AppRate setMinLaunchesUntilPrompt(long minLaunchesUntilPrompt) {
this.minLaunchesUntilPrompt = minLaunchesUntilPrompt;
return this;
}

/**
* @param minDaysUntilPrompt The minimum number of days before showing the rate dialog.<br/>
* Default value is 0 days.
* @return This {@link AppRate} object to allow chaining.
*/
public AppRate setMinDaysUntilPrompt(long minDaysUntilPrompt) {
this.minDaysUntilPrompt = minDaysUntilPrompt;
return this;
}

/**
* @param showIfCrash If <code>false</code> the rate dialog will not be shown if the application has crashed once.<br/>
* Default value is <code>false</code>.
* @return This {@link AppRate} object to allow chaining.
*/
public AppRate setShowIfAppHasCrashed(boolean showIfCrash) {
showIfHasCrashed = showIfCrash;
return this;
}

/**
* Reset all the data collected about number of launches and days until first launch.
* @param context A context.
*/
public static void reset(Context context) {
context.getSharedPreferences(PrefsContract.SHARED_PREFS_NAME, 0).edit().clear().commit();
Log.d(TAG, "Cleared AppRate shared preferences.");
}

/**
* Display the rate dialog if needed.
*/
public void init() {

Log.d(TAG, "Init AppRate");

if (preferences.getBoolean(PrefsContract.PREF_DONT_SHOW_AGAIN, false) || (
preferences.getBoolean(PrefsContract.PREF_APP_HAS_CRASHED, false) && !showIfHasCrashed)) {
ExitApp xt = new ExitApp();
xt.exitMyApp();
return;
}

if (!showIfHasCrashed) {
initExceptionHandler();
}

editor = preferences.edit();

// Get and increment launch counter.
long launch_count = preferences.getLong(PrefsContract.PREF_LAUNCH_COUNT, 0) + 1;
editor.putLong(PrefsContract.PREF_LAUNCH_COUNT, launch_count);

// Get date of first launch.
Long date_firstLaunch = preferences.getLong(PrefsContract.PREF_DATE_FIRST_LAUNCH, 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong(PrefsContract.PREF_DATE_FIRST_LAUNCH, date_firstLaunch);
}

// Show the rate dialog if needed.
if (launch_count >= minLaunchesUntilPrompt) {
if (System.currentTimeMillis() >= date_firstLaunch + (minDaysUntilPrompt * DateUtils.DAY_IN_MILLIS)) {
System.out.println("days..."+date_firstLaunch+"plus days "+(minDaysUntilPrompt * DateUtils.DAY_IN_MILLIS));
showDefaultDialog();
}
}
else
{
ExitApp xt = new ExitApp();
xt.exitMyApp();
}
editor.commit();
}

/**
* Initialize the {@link ExceptionHandler}.
*/
private void initExceptionHandler() {

Log.d(TAG, "Init AppRate ExceptionHandler");

UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();

// Don't register again if already registered.
if (!(currentHandler instanceof ExceptionHandler)) {
// Register default exceptions handler.
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(currentHandler, hostActivity));
}
}

/**
* Shows the default rate dialog.
* @return
*/
private void showDefaultDialog() {

// Log.d(TAG, "Create default dialog.");

String title = "Enjoying this ap?";
String loveit = "Love it";
String likeit = "Like it";
String hateit = "Hate it";

new AlertDialog.Builder(hostActivity)
.setTitle(title)
.setIcon(R.drawable.ic_icon)
//.setMessage(message)
.setNeutralButton(likeit, this)
.setPositiveButton(loveit, this)
.setNegativeButton(hateit, this)
.setOnCancelListener(this)
.setCancelable(true)
.create().show();
}

@Override
public void onCancel(DialogInterface dialog) {

Editor editor = preferences.edit();
editor.putLong(PrefsContract.PREF_DATE_FIRST_LAUNCH, System.currentTimeMillis());
editor.putLong(PrefsContract.PREF_LAUNCH_COUNT, 0);
editor.commit();
}

/**
* @param onClickListener A listener to be called back on.
* @return This {@link AppRate} object to allow chaining.
*/
public AppRate setOnClickListener(OnClickListener onClickListener){
clickListener = onClickListener;
return this;
}

@Override
public void onClick(DialogInterface dialog, int which) {

switch (which) {
case DialogInterface.BUTTON_POSITIVE:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(hostActivity);
// set title
alertDialogBuilder.setTitle("Rate us 5 stars");
alertDialogBuilder.setIcon(R.drawable.ic_icon);
// set dialog message
alertDialogBuilder
.setMessage("Would you be so kind to rate us in playstore?")
.setCancelable(true)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
editor.putBoolean(PrefsContract.PREF_DONT_SHOW_AGAIN, true);
// if this button is clicked, open playstore
try
{
hostActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + hostActivity.getPackageName())));
}catch (ActivityNotFoundException e) {

hostActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + hostActivity.getPackageName())));
}
editor.commit();
}
})
.setNeutralButton("Later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// if this button is clicked, just close and show again the popup dialog on third time exit show again
editor.putBoolean(PrefsContract.PREF_LAUNCH_COUNT, true);
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
editor.putBoolean(PrefsContract.PREF_DONT_SHOW_AGAIN, true);
editor.commit();
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});

// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();

// show it
alertDialog.show();
break;

case DialogInterface.BUTTON_NEUTRAL:
AlertDialog.Builder alertDialogBuilder3 = new AlertDialog.Builder(hostActivity);
// set title
alertDialogBuilder3.setTitle("Rate us 5 stars");
alertDialogBuilder3.setIcon(R.drawable.ic_icon);
// set dialog message
alertDialogBuilder3
.setMessage("Would you be so kind to rate us in playstore?")
.setCancelable(true)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
editor.putBoolean(PrefsContract.PREF_DONT_SHOW_AGAIN, true);
// if this button is clicked, open playstore
try
{
hostActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + hostActivity.getPackageName())));
}catch (ActivityNotFoundException e) {
hostActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + hostActivity.getPackageName())));
}
editor.commit();
}
})
.setNeutralButton("Later", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// if this button is clicked, just close and show again the popup dialog on third time exit show again
editor.putBoolean(PrefsContract.PREF_LAUNCH_COUNT, true);
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
editor.putBoolean(PrefsContract.PREF_DONT_SHOW_AGAIN, true);
editor.commit();
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});

// create alert dialog
AlertDialog alertDialog3 = alertDialogBuilder3.create();

// show it
alertDialog3.show();
break;

case DialogInterface.BUTTON_NEGATIVE:
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(hostActivity);
// set title
alertDialogBuilder1.setTitle("Share Feedback");
alertDialogBuilder1.setIcon(R.drawable.ic_icon);
// set dialog message
alertDialogBuilder1
.setMessage("Please help us to improve.")
.setCancelable(true)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
editor.putBoolean(PrefsContract.PREF_DONT_SHOW_AGAIN, true);
editor.commit();
// if this button is clicked, open feedback page
ExitApp ext = new ExitApp();
ext.openFeedback(hostActivity);
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Cancel Dialog Box
dialog.cancel();
}
});

// create alert dialog
AlertDialog alertDialog1 = alertDialogBuilder1.create();

// show it
alertDialog1.show();
break;

default:
editor.putBoolean(PrefsContract.PREF_LAUNCH_COUNT, true);
editor.commit();
break;
}

dialog.dismiss();

if(clickListener != null){
clickListener.onClick(dialog, which);
}
}

public class PrefsContract {

public static final String SHARED_PREFS_NAME = "apprate_prefs";

public static final String PREF_APP_HAS_CRASHED = "pref_app_has_crashed";
public static final String PREF_DATE_FIRST_LAUNCH = "date_firstlaunch";
public static final String PREF_LAUNCH_COUNT = "launch_count";
public static final String PREF_DONT_SHOW_AGAIN = "dont_show_again";
public static final String PREF_DONT_SHOW_IF_CRASHED = "pref_dont_show_if_crashed";
}

public class ExceptionHandler implements UncaughtExceptionHandler {

private UncaughtExceptionHandler defaultExceptionHandler;
SharedPreferences preferences;

// Constructor.
public ExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler, Context context)
{
preferences = context.getSharedPreferences(PrefsContract.SHARED_PREFS_NAME, 0);
defaultExceptionHandler = uncaughtExceptionHandler;
}

public void uncaughtException(Thread thread, Throwable throwable) {

preferences.edit().putBoolean(PrefsContract.PREF_APP_HAS_CRASHED, true).commit();

// Call the original handler.
defaultExceptionHandler.uncaughtException(thread, throwable);
}
}
}

How to notify users to update there app if New version is available on playstore

How to check there is new version of app is available on playstore, notify users to update old apps with new version in android and display yes or no to get them playstore. Just follow the instructions and put the attached code in your app to check the new version of app is available or not. This code check the app version each day if there is any new version update is available on playstore the a popup will appear on app launch as given image below.



 


It will ask user Yes or No to cancel the popup, if user selects Yes then user will be redirected to playstore to update the app if user selects No then the popup will cancel. On next day after completing the time defined for SharedPrefrences key again appear if app is not updated.

 

Just Download the Code Attached in this article and add it in your project.

After adding the code just past one line of code in your onCreate method of your app Main Activity. The code is given below :

 

new UpdateRunnable(this, new Handler()).start();

Performing operations with SQLiteDatabase in android

Android framework provides an API by the name SQLiteDatabase API. This API provides some set of classes and interfaces which are used by an application developer to create database and performing some operation commonly used classes and interfaces are as follows:

  1. SQLiteOpenHelper

  2. SqliteDatabase

  3. Cursor


 

  1. SQliteOpenHelper ((: This is an abstract class that means if an application developer wants to use this class then we should define the sub class of this class. SQLiteOpenHelper class provides us facility to create database, to create tables into database to open database in readable or in writable mode and to append database or to upgrade. SQLiteOpenHelper class provides us a four parametrized constructor which is used by an application developer to create database.


public SQLiteOpenHelper (Context ctx, String dbName, CursorFactory fact, int dbVer)

{

}

Abstract methods of SQLiteOpenHelper class are:

  1. onCreate(SQLiteDatabase db) : This method is invoked only once whenever SQLiteDatabase is open in readable or writable mode for the first time. An application developer may use this method to perform such options which needs to execute only once Like creation of table into database.

  2. onUpgradeDatabase(SQLiteDatabase db, int oldVersion, into newVersion){}


Non-Abstract methods of SQLiteOpenHelper class are:

  1. getReadableDatabase() : This method returns SQLiteDatabase object in readable mode.

  2. getWritableDatabase() : This methods returns SQLiteDatabase object in writable mode.


SQLiteDatabase : This class provides facility to interact with SQLiteDatabase. An application developer may use tthis class to interact (Insertion, Deletion, Update, Select and perform transactions creation of user define functions etc.) with SQLiteDatabase.

Commonly used methods of this class are as follows:

  1. insert(String tableName, String nullColumnbHack, ContentValues cv) : This methods is used to insert a record in SQLiteDatabase table.


ContentValues : Android framework provides this class to hold or to store data in the form of key value pair where key always representss the name of column. It is case sensitive.

ContextValues cv = new ContentValues();

put (String key, Type Value);

put(String key, Type Value) : Method is used to store data in content value object.

 

Let's start with Sample operations to perform with SQLiteDatabase in android Codes a given below :

 

Download Source Code


Do not forget to share with your friends!


 

EmployeeDAO.java

 

package com.tech.dbdao;

import com.tech.dbdto.Employee;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import android.widget.Toast;

public class EmployeeDAO {
public static final String DBNAME = "Employee.db";
public static final String TABLENAME = "EmpDetail";
public static final String TABLEQUERY = "create table EmpDetail(_id integer primary key autoincrement," +
"NAME text, JOB text, SALARY integer)";
public static final int DB_VERSION = 1;
public static final int READ_MODE = 1;
public static final int WRITE_MODE = 2;

Context ctx;
MyHelper helper;
SQLiteDatabase db;

public EmployeeDAO(Context c) {
ctx = c;
helper = new MyHelper(c, DBNAME, null, DB_VERSION);
}

public void saveDate(Employee e)
{
ContentValues cv = new ContentValues();
cv.put("NAME", e.getNAME());
cv.put("JOB", e.getJOB());
cv.put("SALARY", e.getSALARY());
db.insert(TABLENAME, null, cv);
Toast.makeText(ctx, "Record successfully saved with NAME : "+e.getNAME(), Toast.LENGTH_SHORT).show();
}

public Cursor fetchAllEmp()
{
Cursor cr = db.query(TABLENAME, null, null, null, null, null, null);
return cr;
}

public Employee findById(int eid)
{
Employee emp=null;
Cursor cursor=db.query(TABLENAME, null,    "_id=?", new String[]{""+eid}, null,null,null);
if(cursor.moveToFirst())
{
int id=cursor.getInt(0);
String name=cursor.getString(1);
String job=cursor.getString(2);
String sal=cursor.getString(3);
emp=new Employee(name, job, Integer.parseInt(sal));
emp.setId(id);
}
return emp;
}

public void updateEmp(Employee emp)
{
ContentValues row=new ContentValues();
row.put("NAME", emp.getNAME());
row.put("JOB", emp.getJOB());
row.put("SALARY", emp.getSALARY());
db.update(TABLENAME, row,"_id=?",
new String[]{""+emp.getId()});

Toast.makeText(ctx, "One record is updated successfully..."+emp.getNAME(), Toast.LENGTH_LONG).show();
}

public void deleteEmp(int eid)
{
db.delete(TABLENAME, "_id=?", new String[]{""+eid});
Toast.makeText(ctx, "Record has been deleted", Toast.LENGTH_SHORT).show();
}

public void openDB(int MODE)
{
if(MODE == READ_MODE)
{
db = helper.getReadableDatabase();
}
else
{
db = helper.getWritableDatabase();
}
}

class MyHelper extends SQLiteOpenHelper
{

public MyHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase arg0) {
arg0.execSQL(TABLEQUERY);
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub

}

}
}

 

 

Employee.java

 

package com.tech.dbdto;

public class Employee {
int id;
String NAME, JOB;
int SALARY;
public Employee(String nAME, String jOB, int sALARY) {
super();
NAME = nAME;
JOB = jOB;
SALARY = sALARY;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getJOB() {
return JOB;
}
public void setJOB(String jOB) {
JOB = jOB;
}
public int getSALARY() {
return SALARY;
}
public void setSALARY(int sALARY) {
SALARY = sALARY;
}
}

 

MyApplication.java

[caption id="attachment_841" align="alignnone" width="200"]Employee management sample Employee Database management in android sqlite.[/caption]

package com.tech.dbdemo;

import com.tech.dbdao.EmployeeDAO;

import android.app.Application;

public class MyApplication extends Application {
static EmployeeDAO mydao;
@Override
public void onCreate() {
super.onCreate();
mydao = new EmployeeDAO(getApplicationContext());
}
}

 

Home_Activity.java

 

package com.tech.dbdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class Home_Activity extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);

MenuItem itemSave = menu.add("Save");
MenuItem itemDelete = menu.add("Delete");
MenuItem itemFind = menu.add("Find");
MenuItem itemView = menu.add("View");

itemSave.setIntent(new Intent(this, SaveEmployeeData.class));
itemDelete.setIntent(new Intent(this, DeleteEmployee.class));
itemFind.setIntent(new Intent(this, FindEmployee.class));
itemView.setIntent(new Intent(this, ViewAll.class));
return true;
}
}

 

SaveEmployeeData.java

 

package com.tech.dbdemo;

import com.tech.dbdao.EmployeeDAO;
import com.tech.dbdto.Employee;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SaveEmployeeData extends Activity implements OnClickListener{
EditText etName, etJob, etSalary;
Button btnSave, btnNew, btnExit;

EmployeeDAO eDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saverecords_activity);

etName = (EditText)findViewById(R.id.etName);
etJob = (EditText)findViewById(R.id.etJob);
etSalary = (EditText)findViewById(R.id.etSalary);

btnSave = (Button)findViewById(R.id.btnSave);
btnNew = (Button)findViewById(R.id.btnNew);
btnExit = (Button)findViewById(R.id.btnExit);

btnSave.setOnClickListener(this);
btnNew.setOnClickListener(this);
btnExit.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
eDAO = MyApplication.mydao;
eDAO.openDB(EmployeeDAO.WRITE_MODE);
}
@Override
public void onClick(View arg0) {
if(arg0 == btnSave)
{
eDAO.saveDate(new Employee(etName.getText().toString(), etJob.getText().toString(), Integer.parseInt(etSalary.getText().toString())));
}
if(arg0 == btnNew)
{
etName.setText(null);
etJob.setText(null);
etSalary.setText(null);
}
if(arg0 == btnExit)
{
finish();
}
}
}

 

DeleteEmployee.java

[caption id="attachment_840" align="alignnone" width="200"]Delete an employee Delete an employee record[/caption]

package com.tech.dbdemo;

import com.tech.dbdao.EmployeeDAO;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class DeleteEmployee extends Activity implements OnClickListener {
TextView tvfind;
Button btnFind, btnDel;

EmployeeDAO eDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.findbyid_activity);

tvfind = (TextView)findViewById(R.id.tvfindid);

btnFind = (Button)findViewById(R.id.btnFindid);
btnFind.setText("Delete");
btnFind.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
eDAO = MyApplication.mydao;
eDAO.openDB(EmployeeDAO.WRITE_MODE);
}
@Override
public void onClick(View arg0) {
if(arg0 == btnFind)
{
eDAO.deleteEmp(Integer.parseInt(tvfind.getText().toString()));
}
}
}

 

findbyid_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#088A4B"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<LinearLayout android:id="@+id/linearLayout1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:weightSum="1.0"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:text="ID"
android:id="@+id/textView1"
android:layout_weight=".7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<EditText android:text=""
android:id="@+id/tvfindid"
android:hint="Enter employee id"
android:layout_weight=".3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></EditText>
</LinearLayout>
<Button android:text="Find"
android:id="@+id/btnFindid"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="50dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Button>
</LinearLayout>

FindEmployee.java

[caption id="attachment_839" align="alignnone" width="200"]Find employee id Find employee by id[/caption]

package com.tech.dbdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FindEmployee extends Activity implements OnClickListener{
TextView tvfind;
Button btnFind;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.findbyid_activity);

tvfind = (TextView)findViewById(R.id.tvfindid);

btnFind = (Button)findViewById(R.id.btnFindid);
btnFind.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
if(arg0 == btnFind)
{
Intent intnt = new Intent(this, UpdateEmp_Activity.class);
intnt.putExtra("id", tvfind.getText().toString());
startActivity(intnt);
}
}
}

 

saverecords_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#088A4B"
android:layout_height="match_parent" android:orientation="vertical">
<LinearLayout android:layout_width="match_parent" android:weightSum="1.0" android:id="@+id/linearLayout1" android:layout_height="wrap_content">
<TextView android:text="Name" android:layout_weight=".7" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:layout_weight=".3" android:hint="Enter name" android:id="@+id/etName" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:weightSum="1.0" android:id="@+id/linearLayout2" android:layout_height="wrap_content">
<TextView android:text="Job" android:layout_weight=".7" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:layout_weight=".3" android:hint="Enter job" android:id="@+id/etJob" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:weightSum="1.0" android:id="@+id/linearLayout3" android:layout_height="wrap_content">
<TextView android:text="Salary" android:layout_weight=".7" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:layout_weight=".3" android:hint="Enter salary" android:id="@+id/etSalary" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:weightSum="1.0" android:id="@+id/linearLayout4" android:layout_height="wrap_content">
<Button android:text="Save" android:layout_weight=".33" android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="New" android:layout_weight=".34" android:id="@+id/btnNew" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Exit" android:layout_weight=".33" android:id="@+id/btnExit" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
</LinearLayout>

 

SaveEmployeeData.java

[caption id="attachment_838" align="alignnone" width="200"]Save and update employee Save and update employee information[/caption]

package com.tech.dbdemo;

import com.tech.dbdao.EmployeeDAO;
import com.tech.dbdto.Employee;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SaveEmployeeData extends Activity implements OnClickListener{
EditText etName, etJob, etSalary;
Button btnSave, btnNew, btnExit;

EmployeeDAO eDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saverecords_activity);

etName = (EditText)findViewById(R.id.etName);
etJob = (EditText)findViewById(R.id.etJob);
etSalary = (EditText)findViewById(R.id.etSalary);

btnSave = (Button)findViewById(R.id.btnSave);
btnNew = (Button)findViewById(R.id.btnNew);
btnExit = (Button)findViewById(R.id.btnExit);

btnSave.setOnClickListener(this);
btnNew.setOnClickListener(this);
btnExit.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
eDAO = MyApplication.mydao;
eDAO.openDB(EmployeeDAO.WRITE_MODE);
}
@Override
public void onClick(View arg0) {
if(arg0 == btnSave)
{
eDAO.saveDate(new Employee (etName.getText().toString(), etJob.getText().toString(), Integer.parseInt(etSalary.getText().toString())));
}
if(arg0 == btnNew)
{
etName.setText(null);
etJob.setText(null);
etSalary.setText(null);
}
if(arg0 == btnExit)
{
finish();
}
}
}

 

updateemp_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#088A4B"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<LinearLayout android:id="@+id/linearLayout5" android:weightSum="1.0" android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView android:text="ID" android:id="@+id/textView4" android:layout_width="wrap_content"  android:layout_weight=".3" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/ETID" android:layout_width="wrap_content"  android:layout_weight=".7" android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout1" android:weightSum="1.0" android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView android:text="NAME" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_weight=".3" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/ETNAME" android:layout_width="wrap_content" android:layout_weight=".7" android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout2" android:weightSum="1.0" android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView android:text="JOB" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_weight=".3" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/ETJOB" android:layout_width="wrap_content" android:layout_weight=".7" android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout3" android:weightSum="1.0" android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView android:text="SALARY" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_weight=".3" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/ETSAL" android:layout_width="wrap_content" android:layout_weight=".7" android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout4" android:weightSum="1.0" android:layout_width="match_parent" android:layout_height="wrap_content">
<Button android:text="Update" android:id="@+id/BTNUPDATE" android:layout_width="wrap_content" android:layout_weight=".5" android:layout_height="wrap_content"></Button>
<Button android:text="Exit" android:id="@+id/BTNEXIT" android:layout_width="wrap_content" android:layout_weight=".5" android:layout_height="wrap_content"></Button>
</LinearLayout>

</LinearLayout>

 

UpdateEmp_Activity.java

 

package com.tech.dbdemo;

import com.tech.dbdao.EmployeeDAO;
import com.tech.dbdto.Employee;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class UpdateEmp_Activity extends Activity implements OnClickListener{
EmployeeDAO eDAO = null;
Employee emp = null;
EditText etid, etname, etjob, etsal;
Button btnupdate, btnexit;
@Override
protected void onCreate(Bundle savedInstanceState){
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.updateemp_activity);

etid = (EditText)findViewById(R.id.ETID);
etname = (EditText)findViewById(R.id.ETNAME);
etjob = (EditText)findViewById(R.id.ETJOB);
etsal = (EditText)findViewById(R.id.ETSAL);

btnupdate = (Button)findViewById(R.id.BTNUPDATE);
btnexit = (Button)findViewById(R.id.BTNEXIT);

btnupdate.setOnClickListener(this);
btnexit.setOnClickListener(this);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
eDAO = MyApplication.mydao;
eDAO.openDB(EmployeeDAO.WRITE_MODE);
Intent intnt = getIntent();
String id = intnt.getStringExtra("id");
emp = eDAO.findById(Integer.parseInt(id));
etid.setText(id);
Log.d("NAME ",emp.getNAME());
etname.setText(emp.getNAME());
etjob.setText(emp.getJOB());
int salary = emp.getSALARY();
etsal.setText(""+salary);
}
@Override
public void onClick(View arg0) {
if(arg0 == btnupdate)
{
eDAO.updateEmp(emp);
}
else if(arg0 == btnexit)
finish();
}
}

allemplist_activity.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#088A4B"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:id="@+id/lvEmplist" android:layout_width="match_parent" android:layout_height="wrap_content"></ListView>
</LinearLayout>

 

listdetailholder_layout.xml

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="1.0"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:text=""
android:id="@+id/tvID"
android:textColor="#F8ECE0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView android:text=""
android:id="@+id/tvNAME"
android:layout_below="@+id/tvID"
android:textColor="#F8ECE0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView android:layout_width="wrap_content"
android:text=""
android:id="@+id/tvJOB"
android:textColor="#F8ECE0"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"></TextView>
<TextView android:layout_width="wrap_content"
android:text=""
android:layout_below="@+id/tvJOB"
android:textColor="#F8ECE0"
android:id="@+id/tvSALARY"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"></TextView>
</RelativeLayout>

 

ViewAll.java

[caption id="attachment_837" align="alignnone" width="200"]View All Employee List View All Employee List. Name, Salary, Designation, ID[/caption]

package com.tech.dbdemo;

import com.tech.dbdao.EmployeeDAO;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ViewAll extends Activity {
ListView lvEmp;
EmployeeDAO eDAO;
SimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.allemplist_activity);

lvEmp = (ListView)findViewById(R.id.lvEmplist);
TextView tv = new TextView(this);
tv.setText("Following details of employees are : ");
lvEmp.addHeaderView(tv);
}
@Override
protected void onStart() {
super.onStart();
eDAO = MyApplication.mydao;
eDAO.openDB(EmployeeDAO.READ_MODE);
Cursor c = eDAO.fetchAllEmp();
adapter = new SimpleCursorAdapter (this, R.layout.listdetailholder_layout, c, new String[]{"_id", "NAME", "JOB", "SALARY"}, new int[]{R.id.tvID, R.id.tvNAME, R.id.tvJOB, R.id.tvSALARY});
lvEmp.setAdapter(adapter);
}
}

SQLite Database in android

Today we are going to learn about SQLite Database, How to perform operations insert, update, search , delete and list all details in android. The android framework provides some classes by the name SQLiteDatabase, SQLiteOpenHelper and ContentValues.

 

SQLite is an embedded relational database which provides all the functionalities which are provided by a normal relational external database like inserting new record in table, deleting record from t able, updating existing record in table, fetching records from table managing transactions, creating procedures and functions etc.

Due to an embedded database it doesn't require any third party proprieted database drivers as well as it doesn't consume large amount of memory.

 

SQLite3  => This tool resides in android sdk/tools with sqlite database whatever the operation we want to perform on database like insert delete, update, search etc...

adb(Android Debug Bridge)  => This tool resides in android sdk/platform_tools direcotry. This tool provides facility to interact with an emulator.

sqlite3 <database_name.db> => This command is used to create or open sqlite database. This command opens database if it is already created.

tables =>This command is used to see list of tables.

.header on => This command is used to enable header of table.

.mode tabs => It is used to see data in tabular format.

.mode line => It is used to data line by line.

.exit => It is used to exit from sqlite3 database.

 

 

Do not forget to share with your friends!

What is Layout?



Layout : It is used to arrange components in some predefined manner is known as a layout.Linear Layout : To arrange the component linearly is known as LinearLayout. LinearLayout arranges the componentss in single layout that is in a vertical line (column) or in a Horizontal Line(Rows).

Android framework provides a classs by the name linear layout this class provides us some constructor to initialize this class and some methods to interact with object of this class.

Commonly used constructor and methods of LinearLayout are as follows:

1.    public LinearLayout(Context ctx)
{
--------------------
}

E.g. LinearLayout ll = new LinearLayout(this);

# setOrientation(int Orientation);
Method of LinearLayout is used to set orientation of layout that is whether the components are arranged in vertically of in horizontally.
LinearLayout class provides us some state find integer constant which are used by application developer to set orientation of layout.

Signature :
public void setOrientation(int Orientation)
{
------------------------------
}

publiic static final int HORIZONTAL = 1;
public static final int VERTICAL = 2;

The constant 1 is used to arrange horizontally and the constant 2 is used to to arrange vertically.

Example :
ll.setOrientation(LinearLayout.HORIZONTAL);
Components of layouts will be arranged horizontally

ll.setOrienation(LinearLayout.VERTICAL);
Components of layouts will be arranged vertically

Note: Default orientation of LinearLayout is horizontal.

# setOrientation(LayoutParams lp);
Method is used to set the parameters that is the width, height and weight of Linearlayout. This method receives the reference of LayoutParams as a parameter.

Signature:
public void setLayoutParams(LayoutParams lp)
{
}

E.g.  LayoutParams lp = new LayoutParams(LayoutParams.fill_parent, LayoutParams.wrap_content);
ll.setLayoutParams(lp);

Let we want to create a layout as given below:
LinearLayout projects-codes.blogspot.in

The xml code will be as follows given below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"  >

<LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:weightSum="1.0">
<TextView android:text="Name" android:id="@+id/textView1" android:textSize="25sp" android:layout_weight="0.7" android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/etName" android:layout_width="match_parent" android:layout_weight="0.3" android:layout_height="wrap_content"></EditText>
</LinearLayout>

<LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:weightSum="1.0">
<TextView android:text="Job" android:id="@+id/textView1" android:textSize="25sp" android:layout_weight="0.7" android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/etJob" android:layout_width="match_parent" android:layout_weight="0.3" android:layout_height="wrap_content"></EditText>
</LinearLayout>

<LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:weightSum="1.0">
<TextView android:text="Salary" android:id="@+id/textView1" android:textSize="25sp" android:layout_weight="0.7" android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/etSal" android:layout_width="match_parent" android:layout_weight="0.3" android:layout_height="wrap_content"></EditText>
</LinearLayout>

<LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:weightSum="1.0">
<Button android:text="Save" android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight=".33"></Button>
<Button android:text="New" android:id="@+id/btnNew" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight=".34"></Button>
<Button android:text="Exit" android:id="@+id/btnExit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight=".33"></Button>

</LinearLayout>

</LinearLayout>

android:weightSum is the attribute of Layout used to set width in percentage.
android:layout_weight is attribute of components(Button, TextView, EditText etc.)



Application tools need for android app development


Application tools need for android app development.

To develop android apps we need android SDK contains the API libraries and developer tools to build, debug and develop android apps.

If you are new to develop android apps then you must use ADT Bundle to quickly start android app development.

You can download it from developer.android.com site click here to go >> Download Eclipse ADT

Directory Structure of Android

Directory Structure of Android :
The arrangement of folders in any android application is known as directory structure of android.
The directory structure of android is given below :




Directory src :
This directory contains the source code of any application with ".java" extension.

Directory gen :
This directory contains the auto generated R.java file which is reusable java file.
R.java is also know as reusable java class. It is an auto generated java file that means we can not modify this class manually or by hand.

This java file is generated by AAPT(Android Asset Packaging Tools). This tool receives resource data as an input and generate R.java file as an output.
R.java file works as a mediator file between activities and xml components defined inside resource.
R.java file contains some static final inner classes like drawable, layout, id, etc...

Directory res :
 The res directory is known as resource directory. It contains drawable-ldpi, drawable-mdpi, drawable-hdpi, these drawable directory is contains the image resources like icon and other images with .png extension.
Directory layout contains xml files (User interface designed by developer)  the user interface is designed using xml code in android.

Directory value :
It is used to put data in form of key value pair.

AndroidManifest.xml
It is a meta data file which is used by ARE(Android Runtime Environment) to launch application.

Activity and It's Life Cycle

Activity : An activity represents visible component of android. It is used by  an application developer to interact with end user.

          Android framework provides a class by the name android.app.Activity this class provides us life cycle method of activity these methods are override by application developer to perform there tasks. An application developer can use this class by defining sub class of activities.

The life cycle of activity can be divided in three state:
1. Active State
2. Visible State
3. Inactive State/Invisible State

Active State : An active state of an activity represents activity is visible as well as it has user focus. The life cycle of this state is managed by onResume() and onPause() life cycle method of activity.

Visible State
: Visible sate of activity represents that activity is visible it don't have user focus life cycle of this state is managed by onStart() and onStop() life cycle method of activity.

Inactive State/Invisible State : The invisible state of activity represents that niether activity is visible nor it have user focus. Life cycle of this state is managed by onCreate() and onDestroy() life cycle method of activity.

Activity Life cycle
activiy life cycle






Android Framework Modules

We can divide android framework in five basic modules which are as follows:

1. Activity
2. Intent
3. Broadcast Receiver
4. Services
5. Content Provider

Activity : An activity represents visible component of android which is used to interact with end users. Activities are light frames in awt, swing, of forms in case of web applications.

Intent : An intent is used to provide communication among multiple components of android it works as a communicator.

Broadcast Receiver : A broadcast receiver is used to perform some short time consuming on the occurrence of some particular event.

Services : Services is used to perform long time consuming background performs it doesn't require any user interaction.

Content Provider : It provides facility to share a database among multiple application of android system.

Android Virtual Machine

Virtual Machine : It is software implementation of any machine. It doesn't exist physically. It is used to execute a program or application.

The most important property of virtual machine is that any application or program running inside virtual machine is restricted to its resource and this abstraction is provided by virtual machine.

Virtual Machine is divided in two parts :
1.  System Virtual Machine 
2.  Process Virtual Machine / Application Virtual Machine

System Virtual Machine represents functionality of operating system. It is used to execute the program or application.

Process Virtual Machine is divided in two parts :
1.  Stack Based Virtual Machine  (JVM)
2.  Register Based Virtual Machine  (DVM)                                 

Stack Based Virtual Machine : It is faster but it consumes large amount of memory.

e.g. : JVM

Register Based Virtual Machine : It is slower but it consumes less amount of memory.

eg. : DVM


Note: Register based virtual machine gives 33.3% better performance then stack based virtual machine in case of mobile application.

Delvik Virtual Machine : It is a register based virtual machine developed by "Den Bronstien" it doesn't execute java byte code rather it executes its own byte code format which is know as delvik code.


Android Definition

Android : Android is an open source platform for mobile application provided
by google which consist of following :

1. Mobile OS
2. Application Devlopment Platform
3. Android Runtime Environment
4. Net of some dummy applications which are being developed in android

Android is a stack of software provided by google which facilitate to develop,
to deploy and to execute the mobile application which is being developed in android.

Native Application
3rd Party Application

(Application Development Framework)
Set of predefined classes and interfaces which are used
by developer to change the productivity of application
development.

Set of native Libraries which are
written in C/C++ such as
Bluetooth lib. , WIFI lib. , Camera
lib. etc. .

Delvik

Virual

Machine


                                            (Linux Kernels)

Devices Drivers
Memory Management
Process Management
Power Management


                                      Stack of Software Warms 
                                          OR 
                          Architecture of Android 


Smart Phones and Normal Phones

Nokia _________ Symbian(Normal Phone)
|__________ windows Phone(Smart Phone)
|__________ Android(Smart Phone)

Samsung _______ Wada(Normal Phone)
|__________ Android(Smart Phone)

Black Berry ___ BBX(Smart Phone)

Iphone ________ IOS(Smart Phone)


History of Smart Phones




Smart Phones
|___________ Black Berry --> Product of RIM(Research In Motion)
| Launced in 1999
| It is father of Smart Phone
|
|___________ Iphone --> Launched by Apple Inc. in 2007
|
|___________ Android --> First tried to develop by Android Inc.
Founders of Android --> Andy Robin, Rich Minor, Nick Sears and Chris White
but was getting problem in development then Google dealed with them in
2005 in android development (Google + Android Inc.)
But unable to do so, Google contacted to OHA(Open Handset Alliance) in 2007
Then finally launched the android smart phones in 2008.



What is JDK, JRE and JVM?

JDK (Java Development Kit)

Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc.. Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method. You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient. JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries. JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file.

JRE (Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system. The Java Virtual Machine provides a platform-independent way of executing code; That mean compile once in any machine and run it any where(any machine).

JVM (Java Virtual Machine)

As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file. ‘.class’ file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.

The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.

There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.

Forgot password AND CSS Stylesheets

Find the given code below for forgot password the part the student section. Here the student will be able to find the new password if he/she forgot the password.

Save the code in new file with name "forgot-password.php".


<?php
    include"../scripts/validaitons.php";
    $email="";
    $invalid="";
    $stats=true;
    if(isset($_POST['submit']))
    {
        if($_POST['emailid']=="")
        {
            $email="Please provide Email ID";
            $stats=validateEmail();
            if($stats==false)
            {
                $invalid="Please provide a valid Email ID";
            }
        }
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
      <title>Forgot Password</title>
      <link rel="STYLESHEET" type="text/css" href="../styles/student_forms.css" />
</head>
<body>

<!-- Form Code Start -->
<?php include("header.php"); ?>
<div id='student_forms' >
    <form name="forgot_password" method='post' accept-charset='UTF-8'>
    <fieldset>
    <legend>Forgot Password</legend>
    <div class='required'>* Required Fields :</div>
    <div class="container"><span class='required'>*<span>
        <label class='labels'>Your Email :</label></br>
        <input type="text" name="emailid" maxlength="50">
        <div class='required' align="right"><?php echo $email; echo $invalid; ?></div>
        <div class='short_msg'>A link to reset your password will be sent to the registered email address.</div>
    <input type="submit" name="submit" value="Submit"/></div>
    </fieldset>
    </form>
</div>
<?php include("footer.php"); ?>
</body>
</html>




=========================================================
Save the stylesheet with name "admission_form.css"


#admission_form select,
#admission_form option
{
    background-color : #ffff99;
}
#admission_form select
{
    font-family : Arial,  sans-serif;
    font-size: 0.7em;
    color : #000;
    padding : 2px;
    border : 1px solid #999;
    border-radius: 5px;
}
#admission_form legend
{
    font-family : Arial, sans-serif;
    font-size: 1.3em;
    font-weight:bold;
}
#admission_form .short_msg
{
    font-family : Arial, sans-serif;
    font-size: 0.7em;
    color:#333;
}
#admission_form fieldset
{
    border-style:ridge;
    border-width:10px;
    border-color:#98bf21;
    margin:auto;
    width: 230px;
    padding:20px;
    border:1px solid #ccc;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    -khtml-border-radius: 10px;
    border-radius: 10px;
}
#admission_form .labels
{
    font-family:Arial, sans-serif;
    font-size:0.8em;
    color:#333;
}
#admission_form input[type="text"],
#admission_form input[type="password"]
{
    font-family : Arial, Verdana, sans-serif;
    font-size: 0.8em;
    color : #000;
    padding : 3px;
    border : 1px solid #999;
    border-radius: 5px;
}
#admission_form .smallinput
{
    height:18px;
    width:100px;
}
#admission_form input[type="submit"]
{
    width:80px;
    height:30px;
    color : #009;
    background-color : #ffff99;
}
#admission_form input[type="text"],
#admission_form input[type="password"]
{
    background-color : #ffff99;
}

#admission_form .required
{
    font-family : Arial, sans-serif;
    font-size: 0.8em;
    color:#FF0000;
}
.mainDiv
{
    margin:auto;
    padding:20px;
    width: 800px;
    //height:200px;
    //border:red solid;
    border-radius: 10px;
}
.heading
{
    background:BROWN;
}
.divleft
{
    float:left; margin-right:20px;
}
.divright
{
    float:left; margin-right:20px;
}



===========================================================

Save the new file with name "student_forms.css" code is given below :

#student_forms legend
{
    font-family : Arial, sans-serif;
    font-size: 1.3em;
    font-weight:bold;
}
#student_forms .short_msg
{
    font-family : Arial, sans-serif;
    font-size: 0.7em;
    color:#333;
}
#student_forms fieldset
{
    border-style:ridge;
    border-width:10px;
    border-color:#98bf21;
    margin:auto;
    width: 440px;
    height:240px;
    padding:30px;
    border:1px solid #ccc;
    border-radius: 10px;
}
#student_forms .container
{
    margin-top:8px;
    margin-bottom:10px;
    float:right;
}
#admin_forms .containerleft
{
    margin-top:8px;
    margin-bottom:10px;
    float:right;
}
#student_forms .labels
{
    font-family:Arial, sans-serif;
    font-size:1em;
    color:#333;
}
#student_forms input[type="text"],
#student_forms input[type="password"]
{
    font-family : Arial, Verdana, sans-serif;
    font-size: 0.9em;
    color : #000;
    padding : 3px;
    border : 1px solid #999;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    -khtml-border-radius: 5px;
    border-radius: 5px;
}
#student_forms input[type="text"],
#student_forms input[type="password"]
{
    height:18px;
    width:220px;
}
#student_forms input[type="submit"]
{
    width:80px;
    height:30px;
    padding-left:0px;
}
#student_forms input[type="text"]:focus,
#student_forms input[type="password"]:focus
{
    color : #009;
    border : 1px solid #990000;
    background-color : #ffff99;
    font-weight:bold;
}

#student_forms .required
{
    font-family : Arial, sans-serif;
    font-size: 0.8em;
    color:#FF0000;
}
.mainDiv
{
    margin:auto;
    padding:20px;
    width: 800px;
    //height:200px;
    //border:red solid;
    border-radius: 10px;
}
.heading
{
    background:BROWN;
}



==========================================

Save the given code below with new file name "style.css"

/* Label */
samp
{
    width: 300px;
    padding-left: 20px;
    margin: 5px;
    float: left;
    text-align: left;
    font-family:Arial, sans-serif;
    font-size:1em;
    color:#333;
}
kbd
{
    width: 60px;
    padding-left: 20px;
    margin: 5px;
    float: left;
    text-align: left;
    font-family:Arial, sans-serif;
    font-size:1em;
    color:#333;
}
select
{
    margin: 5px;
    padding: 0px;
    float: left;
}
span
{
    width: 10px;
    padding-left: 20px;
    margin: 5px;
    float: left;
    text-align: left;
    font-family : Arial, sans-serif;
    font-size: 0.8em;
    color:#FF0000;
   
}
/* Input, Textarea */
input[type="text"]
{
    margin: 5px;
    padding: 0px;
    float: left;
}
pre
{
    margin: 5px;
    padding: 0px;
    float: left;
}
label
{
    font-family : Arial, sans-serif;
    font-size: 0.8em;
    color:#FF0000;
    float: left;
}
input[type="checkbox"]
{
    margin: 5px;
    padding: 0px;
    float: left;
}
/* BR */

br
{
    clear: left;
}
.required
{
    color:#FF0000;
}


===========================================

all stylesheet files must be save in given directory path "localhost/MyProject/styles/"

Application Submited Successful And Header or Footer Part for Student Pages

This post is about the Request successfully submitted page to display the message here and header or footer part of the student pages.

Save the code given below in new files.. 1st is name "succesful.php"

<?php
    include("../db.php");
    include("../functions.php");
    if (isset($_GET['edit']))
    {   
        $enrolmentno = $_GET['edit'];
        $link = "<a href='index.php?edit=$enrolmentno'><img src='../images/gohome.png' title='Go Home'></a>";
    }
    if(isset($_POST['submit']))
    {
        mysql_query("update program_details set change_status=1 where enrolmentno = $enrolmentno");
        header("Location: index.php?edit=$enrolmentno");
        echo "Request Successfully Submitted.";
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
      <title>Welcome To Online Admission(Student Zone)</title>
      <link rel="STYLESHEET" type="text/css" href="../styles/admission_form.css" />
</head>
<body >
<?php include("header.php");?>
<div class='mainDiv'>
    <div><font size="4" name="sans-serif" color="white"><div class="heading" align="center"><b>Welcome To Distance Education University Online Admission Form</b></br>Student Zone</div></font></br></br>
    <pre align="center">Your Request Has Been Successfully Submitted For Approval.
   
   
    <?php echo $link; ?>
       
    </pre>
</div></br>
<?php include("footer.php");?>
</body>
</html>





The code given below is of header part save the code in new file name "header.php".

<div style="margin:auto;width:850px;border-color:#98bf21;">
    <img src="../images/banner.png">
</div>


The last code given below is for footer part the page save it with name "footer.php".

</br>
<div style="margin:auto;width:850px;border-color:#98bf21;height:125px;" align="left">
    <img src="../images/footer.png">
</div>

Student Detail Page

This page is to display the student detail and registration status of year or semester and other made requests by the student. Save the code in new file name "detail.php". Kindly complete the code your self it's incomplete.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
      <title>Welcome To Online Admission(Student Zone)</title>
      <link rel="STYLESHEET" type="text/css" href="../styles/admission_form.css" />
</head>
<body >
<?php include("header.php");?>
<div class='mainDiv'>
    <div><font size="4" name="sans-serif" color="white"><div class="heading" align="center"><b>Welcome To Distance Education University Online Admission Form</b></br>Student Zone</div></font></br></br>
    <div align="center">
        <table style="border:1px solid black;border-radius:10px;">
            <tr>
                <td>
                    <table style="border:1px solid black;border-radius:10px;">
                        <tr>
                        <td align=center colspan=3 style="border:1px solid black;border-radius:10px;">Welcome Sunni Kumar</br>Program : MCA</br>Enrolment No : <tr>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Admission Year</label>
                                <td>:</td>
                            </td>
                            <td>
                                <input type="text" name="stuname">
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Admission valid upto</label>
                            </td>
                            <td>:</td>
                            <td>
                                <input type="text" name="programcode">
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Father's Name</label>
                            </td>
                            <td>:</td>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Current Address</label>
                            </td>
                            <td>:</td>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Regional Center</label>
                            </td>
                            <td>:</td>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Study Center</label>
                            </td>
                            <td>:</td>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Mobile No.</label>
                            </td>
                            <td>:</td>
                        </tr>
                        <tr>
                            <td>
                                <label class='labels'>Email ID</label>
                            </td>
                            <td>:</td>
                        </tr>
                    </table>   
                </td>
                <td>
                    <table style="border:1px solid black;width:350px;height:266px;border-radius:10px;">
                    <tr>
                        <td colspan=3 align="center">
                            <label >Request Made If Any</label>
                        </td>
                       
                    </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td colspan=2>
                    <table style="border:1px solid black;width:730px;border-radius:10px;">
                <tr>
                    <td align=center>Course Registration Details</td>
                </tr>
            </table>
                </td>
            </tr>
        </table>
    </div>
</div></br>
<?php include("footer.php");?>
</body>
</html>