Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
Program to print Fibonacci Series in java
Program to print Fibonacci
Series in java
This program is about to print the series of Fibonacci.
The program is written as you can understand loop wise while it’s running. You’ll
easily understand the flow of code and loop of the Fibonacci series.
Find below the program written.
import java.util.Scanner;
public class MyClass {
public static
void main(String args[]) {
Scanner
scan = new Scanner(System.in);
int n =
scan.nextInt();
int a = 0,
b = 0, c = 1;
for(int i =
0; i < n; i++){
System.out.println("Loop No. "+i);
a = b;
System.out.println("a = b | a = "+b);
b = c;
System.out.println("b = c | b = "+c);
c = a +
b;
System.out.println("c = a + b | c = " + a + " + " +
b);
System.out.println(a+" ");
System.out.println("-----------------------");
}
System.out.println();
a = 0;
b = 0;
c = 1;
for(int i =
0; i < n; i++){
a = b;
b = c;
c = a +
b;
System.out.print(a+" ");
}
}
}
Output:
Program to print the star pattern triangle left to right
This program is about to print the star pattern triangle from left to right the row of triangle is defined 5 here in this program. So, only 5 rows will be printed. There are 2 loops will be execute to print the triangle.
There are one integer variables are used in each loop.
We are using for loop the outer loop will execute till the i variable is less then equals to (<=) row which is 5 and i will be incremented by 1 each time and i is initialized from 0.
In the next inner for loop the k variable we are using and initialized each time from 0 when it comes to inner loop from out loop and loop will execute till count of k is less then i so, each time when the inner loop will execute it will print the "* and space" and k will increment from 1.
After completing inner loop a new line will be printed or the cursor will move to the new line.
/******************************************************************************
Program
to print the star pattern triangle left to right.
*******************************************************************************/
public class Main
{
public
static void main(String[] args) {
int
row = 5;
for(int
i = 0; i <= row; i++){
for(int k = 0; k < i; k++){
System.out.print("* ");
}
System.out.println();
}
}
}
After completing the output is given below:
Output:
If you have any query regarding the program then please ask or comment below.
Program to find the digits from alphanumeric string and find the sum of digits.
This is program is about to find the digits from alpha
numeric string and find the sum of all digits.
We will read the string character wise then it is possible to find the number from string. When we'll read each character we've to use the isDigit function of java which is defined in the Character class. isDigit function allows us to identify the given character is string or alphabet.
/******************************************************************************
Write a program to find the sum of digits found in given
string.
*******************************************************************************/
public class Main
{
public
static void main(String[] args) {
int
sum = 0;
String
str = "sd54s4dfwer46df4d";
for(int
i = 0; i < str.length(); i++){
if(Character.isDigit(str.charAt(i))){
sum
= sum + Integer.parseInt(String.valueOf(str.charAt(i)));
System.out.print(str.charAt(i)+"
");
}
}
System.out.println("Sum
of digits is : "+sum);
}
}
Output:
If you have any question about it then please comment below.
Fetch Contact List from android device
How to fetch Contact list in android to use it in own way. The android OS provides feature to fetch all contacts from android device like Name, Image, Phone No., Email Id. It fetches all contacts from all added accounts like Facebook, Gmail, Watsapp and your android device which stores contacts. This tutorial is about to fetch contact list from an android device.
This example uses the ContactsContract and ContentResolver classes to fetch all contacts from android device. The URI used is CONTENT_URI to fetch contacts.
The above given code will help to fetch all contacts from android device.
This example uses the ContactsContract and ContentResolver classes to fetch all contacts from android device. The URI used is CONTENT_URI to fetch contacts.
ContentResolver cr = this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (Integer.parseInt( cur.getString( cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER ) ) ) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
int e = 0;
while (emailCur.moveToNext()) {
emailContact = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
}
}
The above given code will help to fetch all contacts from android device.
Detect Android App Webview in Php
Sometimes we have an app with webview in android where we use our website as app in android. Where to hold website we use android webview. To identify or detect the app in php websites we need to solve the situation. To do this php provides a predefined variable :
$_SERVER['HTTP_X_REQUESTED_WITH']
This variable matches the package name of android app to identify if user is using our android app or using website.
Example is given below :
if($_SERVER['HTTP_X_REQUESTED_WITH'] == "com.sk.codes") {
echo 'Welcome to Basic Codes android app.';
}
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);
}
}
}
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();
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:
public SQLiteOpenHelper (Context ctx, String dbName, CursorFactory fact, int dbVer)
{
}
Abstract methods of SQLiteOpenHelper class are:
Non-Abstract methods of SQLiteOpenHelper class are:
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:
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 :
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 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 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 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 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. 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);
}
}
- SQLiteOpenHelper
- SqliteDatabase
- Cursor
- 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:
- 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.
- onUpgradeDatabase(SQLiteDatabase db, int oldVersion, into newVersion){}
Non-Abstract methods of SQLiteOpenHelper class are:
- getReadableDatabase() : This method returns SQLiteDatabase object in readable mode.
- 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:
- 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 :
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"]
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"]
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"]
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"]
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"]
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!
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!
Subscribe to:
Posts (Atom)