Database Operations In Android

Introduction

 
In every Android application, we need to save some details on the Android device. For this, there are some options that the Android Operating system provides and those are SQL, File, and SharedPreference. Here, I am going to describe how you can store and retrieve data from Databases in Android. For this, I am using two Activities, one activity contains the Login Page where you can check whether user data exist in the database or not. In RegisterActivity, the user can store his/her details in the database. 
 
For the first one, create the login Activity layout,
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2. xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    
  3. android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    
  4. android:paddingRight="@dimen/activity_horizontal_margin"    
  5. android:paddingTop="@dimen/activity_vertical_margin"    
  6. android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">    
  7.     <TextView    
  8. android:layout_width="wrap_content"    
  9. android:layout_height="wrap_content"    
  10. android:textAppearance="?android:attr/textAppearanceLarge"    
  11. android:text="Login Here"    
  12. android:id="@+id/textView"    
  13. android:layout_alignParentTop="true"    
  14. android:layout_centerHorizontal="true" />    
  15.     <LinearLayout android:layout_width="match_parent"    
  16. android:layout_below="@+id/textView"    
  17. android:id="@+id/userNameLayout"    
  18. android:layout_margin="10dp"    
  19. android:orientation="horizontal"    
  20. android:layout_height="50dp">    
  21.         <TextView    
  22. android:layout_width="0dp"    
  23. android:layout_weight="1"    
  24. android:text="User Name :"    
  25. android:layout_height="wrap_content" />    
  26.         <EditText    
  27. android:layout_width="0dp"    
  28. android:layout_weight="2"    
  29. android:id="@+id/username"    
  30. android:layout_height="wrap_content" />    
  31.     </LinearLayout>    
  32.     <LinearLayout android:layout_width="match_parent"    
  33. android:layout_below="@+id/userNameLayout"    
  34. android:layout_margin="10dp"    
  35. android:orientation="horizontal"    
  36. android:layout_height="50dp"    
  37. android:id="@+id/linearLayout">    
  38.         <TextView    
  39. android:layout_width="0dp"    
  40. android:layout_weight="1"    
  41. android:text="Password :"    
  42. android:layout_height="wrap_content" />    
  43.         <EditText    
  44. android:layout_width="0dp"    
  45. android:id="@+id/password"    
  46. android:inputType="textPassword"    
  47. android:layout_weight="2"    
  48. android:layout_height="wrap_content" />    
  49.     </LinearLayout>    
  50.     <Button    
  51. android:layout_width="wrap_content"    
  52. android:layout_height="wrap_content"    
  53. android:text="Login"    
  54. android:id="@+id/loginButton"    
  55. android:layout_below="@+id/linearLayout"    
  56. android:layout_centerHorizontal="true" />    
  57.     <Button    
  58. android:layout_width="wrap_content"    
  59. android:layout_height="wrap_content"    
  60. android:text="Register User"    
  61. android:id="@+id/registerButton"    
  62. android:layout_below="@+id/loginButton"    
  63. android:layout_centerHorizontal="true" />    
  64.     
  65. </RelativeLayout>   
    This contains two edit texts where the user can enter their user name and password. This contains two buttons: Log in and Register. On clicking the Login button we need to check the database so that the user details exist or not. Another button named Register will call the Register Activity.
    
    
    Now create the Registration layout also,
    1. <?xml version="1.0" encoding="utf-8"?>    
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    3. android:orientation="vertical" android:layout_width="match_parent"    
    4. android:layout_height="match_parent">    
    5.     <TextView    
    6. android:layout_width="wrap_content"    
    7. android:layout_height="wrap_content"    
    8. android:textAppearance="?android:attr/textAppearanceLarge"    
    9. android:text="Register Here"    
    10. android:id="@+id/textView2"    
    11. android:layout_gravity="center_horizontal" />    
    12.     <LinearLayout    
    13. android:orientation="horizontal"    
    14. android:layout_width="match_parent"    
    15. android:layout_height="50dp"    
    16. android:layout_margin="20dp"    
    17. android:layout_gravity="center_horizontal">    
    18.     
    19.         <TextView    
    20. android:layout_width="0dp"    
    21. android:layout_weight="1"    
    22. android:text="Name :"    
    23. android:layout_height="wrap_content" />    
    24.         <EditText    
    25. android:layout_width="0dp"    
    26. android:id="@+id/name"    
    27. android:layout_weight="2"    
    28. android:layout_height="wrap_content" />    
    29.     </LinearLayout>    
    30.     <LinearLayout    
    31. android:orientation="horizontal"    
    32. android:layout_width="match_parent"    
    33. android:layout_height="50dp"    
    34. android:layout_margin="20dp"    
    35. android:layout_gravity="center_horizontal">    
    36.     
    37.         <TextView    
    38. android:layout_width="0dp"    
    39. android:layout_weight="1"    
    40. android:text="User Name :"    
    41. android:layout_height="wrap_content" />    
    42.         <EditText    
    43. android:layout_width="0dp"    
    44. android:id="@+id/userName"    
    45. android:layout_weight="2"    
    46. android:layout_height="wrap_content" />    
    47.     </LinearLayout>    
    48.     <LinearLayout    
    49. android:orientation="horizontal"    
    50. android:layout_width="match_parent"    
    51. android:layout_height="50dp"    
    52. android:layout_margin="20dp"    
    53. android:layout_gravity="center_horizontal">    
    54.     
    55.         <TextView    
    56. android:layout_width="0dp"    
    57. android:layout_weight="1"    
    58. android:text="Password :"    
    59. android:layout_height="wrap_content" />    
    60.         <EditText    
    61. android:layout_width="0dp"    
    62. android:id="@+id/Password"    
    63. android:inputType="textPassword"    
    64. android:layout_weight="2"    
    65. android:layout_height="wrap_content" />    
    66.     </LinearLayout>    
    67.     <Button    
    68. android:layout_width="wrap_content"    
    69. android:layout_height="wrap_content"    
    70. android:text="Register"    
    71. android:id="@+id/registerButton"    
    72. android:layout_gravity="center_horizontal" />    
    73. </LinearLayout>   
    Now comes the main part that is the Database helper class. In Android, there is a class named SQLiteOpenHelper which is an abstract class and is used for the database operations. Firstly, create a class that extends from SQLiteOpenHelper and implement the onCreate() and onUpgrade().
    • onCreate() - It is used for creating the database.
    • onUpgrade() - It is used for upgrading the database if there is a new version available for the database. Please see the class in detail,
      1. public class DBHelper extends SQLiteOpenHelper    
      2. {    
      3.     private static final int VERSION = 1;    
      4.     private static final String DATA_BASE_NAME = "users.db";    
      5.     private static final String TABLE_NAME = "login";    
      6.     private static final String COLUMN_ID = "id";    
      7.     private static final String COLUMN_NAME = "name";    
      8.     private static final String COLUMN_USER_NAME = "username";    
      9.     private static final String COLUMN_PASSWORD = "password";    
      10.     private static final String CREATE_TABLE = "create table " + TABLE_NAME + " (" + COLUMN_ID + " integer primary key not null, " + COLUMN_NAME + " text not null," + COLUMN_USER_NAME + " text not null, " + COLUMN_PASSWORD + " text not null);";    
      11.     private SQLiteDatabase db = null;    
      12.     public DBHelper(Context context) {    
      13.         super(context, DATA_BASE_NAME, null, VERSION);    
      14.     }    
      15.     @Override    
      16.     public void onCreate(SQLiteDatabase sqLiteDatabase) {    
      17.         sqLiteDatabase.execSQL(CREATE_TABLE);    
      18.         db = sqLiteDatabase;    
      19.     }    
      20.     public void registerUser(UserDetails userDetails) {    
      21.         db = this.getWritableDatabase();    
      22.         ContentValues contentValues = new ContentValues();    
      23.         contentValues.put(COLUMN_NAME, userDetails.getName());    
      24.         contentValues.put(COLUMN_PASSWORD, userDetails.getPassword());    
      25.         contentValues.put(COLUMN_USER_NAME, userDetails.getUserName());    
      26.         db.insert(TABLE_NAME, null, contentValues);    
      27.         db.close();    
      28.     }    
      29.     public boolean isUserExists(UserDetails userDetails) {    
      30.         db = this.getReadableDatabase();    
      31.         String querry = "select * from " + TABLE_NAME + " where " + COLUMN_USER_NAME + "='" + userDetails.getUserName() + "' and " + COLUMN_PASSWORD + "='" + userDetails.getPassword() + "'";    
      32.         Cursor cursor = db.rawQuery(querry, null);    
      33.         if (cursor.moveToFirst()) {    
      34.             return true;    
      35.         }    
      36.         return false;    
      37.     }    
      38.     @Override    
      39.     public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}    
      40. }   
      There are two methods, registerUser() and isUserExists() both are interacting with our two Activities for database operations. We also create one model class for setting and getting the details,
      1. public class UserDetails     
      2. {    
      3.     private String userName = null;    
      4.     private String password = null;    
      5.     private String name = null;    
      6.     public String getUserName()     
      7.     {    
      8.         return userName;    
      9.     }    
      10.     public void setUserName(String userName)    
      11.     {    
      12.         this.userName = userName;    
      13.     }    
      14.     public String getPassword()    
      15.     {    
      16.         return password;    
      17.     }    
      18.     public void setPassword(String password)     
      19.         
      20.     {    
      21.         this.password = password;    
      22.     }    
      23.     public String getName() {    
      24.         return name;    
      25.     }    
      26.     public void setName(String name) {    
      27.         this.name = name;    
      28.     }    
      29. }   
        In the LoginActivity button click use this code to check the user data exists in the table or not by using,
        1. if (!TextUtils.isEmpty(userName.getText().toString()) && !TextUtils.isEmpty(password.getText().toString())) {    
        2.     UserDetails userDetails = new UserDetails();    
        3.     userDetails.setPassword(password.getText().toString());    
        4.     userDetails.setUserName(userName.getText().toString());    
        5.     DBHelper dbHelper = new DBHelper(MainActivity.this);    
        6. if(dbHelper.isUserExists(userDetails))    
        7.         Toast.makeText(MainActivity.this"Success", Toast.LENGTH_SHORT).show();    
        8. else    
        9.  Toast.makeText(MainActivity.this"Invalid login", Toast.LENGTH_SHORT).show();    
        10. else {    
        11.     Toast.makeText(MainActivity.this"please enter all the fields", Toast.LENGTH_SHORT).show();    
        12. }   
          And in the Register activity for inserting the table, we can use the following code,
          1. if (!TextUtils.isEmpty(userName.getText().toString()) && !TextUtils.isEmpty(password.getText().toString()) && !TextUtils.isEmpty(name.getText().toString())) {    
          2.     UserDetails userDetails = new UserDetails();    
          3.     userDetails.setName(name.getText().toString());    
          4.     userDetails.setPassword(password.getText().toString());    
          5.     userDetails.setUserName(userName.getText().toString());    
          6.     DBHelper dbHelper = new DBHelper(RegisterActivity.this);    
          7.     dbHelper.registerUser(userDetails);    
          8.     Toast.makeText(RegisterActivity.this"Successfully registered", Toast.LENGTH_SHORT).show();    
          9. else {    
          10.     Toast.makeText(RegisterActivity.this"please enter all the fields", Toast.LENGTH_SHORT).show();    
          11. }   
            In all the DB operations users will be intimated by a toast message as status.
             
            Here are the screenshots
             
              

            Read more articles on Android