CRUD App In Android Studio Using SQLite

Introduction

 
Before creating an app in Android Studio, I will explain in brief about the SQLite database. SQLiteDatabase is the base class for working with an SQLite database in Android, which provides some methods to open, query, update and close the database. 
 
Open Android Studio and start a new Android Studio project
 
 
Then enter the application name and select path for it.
 
 
Click on Next
 
Select Minimum SDK for Phone and Tablet option,
 
 
Click Next and select Blank Activity,
 
 
Click Next and by default, a blank activity with name MainActivity will be displayed,
 
 
Click Finish.
 
 
By default, Hello world will be displayed and the application will look like this with MainActivity.
 
 
In activity_mail.xml, add TextView control.
  1. <TextView    
  2.    android:layout_width="wrap_content"    
  3.    android:layout_height="wrap_content"    
  4.    android:id="@+id/textView"    
  5.    android:layout_centerHorizontal="true"    
  6.    android:textSize="30dp"    
  7.    android:text="CRUD for Student using SQLLite"    
  8. />    
    Add a java class called DBHelper.java to create a database.
     
     
    Extend this DBHelper.java class with SQLLiteOpenHelper class. Create a subclass of the SQLLiteOpenHelper class. This class provides the getReadableDatabase() and getWriteableDatabase() methods to get access to an SQLLiteDatabase object.
    1. package com.test.ppandey.contactapp;    
    2.      
    3.  import android.content.ContentValues;    
    4.  import android.content.Context;    
    5.  import android.database.Cursor;    
    6.  import android.database.DatabaseUtils;    
    7.  import android.database.sqlite.SQLiteDatabase;    
    8.  import android.database.sqlite.SQLiteOpenHelper;    
    9.      
    10.  import java.util.ArrayList;    
    11.  import java.util.HashMap;    
    12.      
    13.  /**  
    14.   * Created by ppandey on 12/15/2015.  
    15.   */    
    16.  public class DBHelper extends SQLiteOpenHelper {    
    17.  public static final String DATABASE_NAME = "contactdb.sqlite";    
    18.  public static final String CONTACTS_TABLE_NAME = "mycontacts";    
    19.  public static final String CONTACTS_COLUMN_ID  = "id";    
    20.  public static final String CONTACTS_COLUMN_STUNAME = "name";    
    21.  public static final String CONTACTS_COLUMN_STUPHONE = "phone";    
    22.  public static final String CONTACTS_COLUMN_STUSTREET = "street";    
    23.  public static final String CONTACTS_COLUMN_STUEMAIL = "email";    
    24.  public static final String CONTACTS_COLUMN_STUCITY = "place";    
    25.      
    26.  private HashMap hp;    
    27.      
    28.  public DBHelper(Context context)    
    29.      {    
    30.  super(context, DATABASE_NAME , null3);    
    31.      }    
    32.      
    33.  @Override    
    34.  public void onCreate(SQLiteDatabase db) {    
    35.          db.execSQL(    
    36.  "create table mycontacts " +    
    37.  "(id integer primary key autoincrement, name text,phone text,email text, street text,place text)"    
    38.  );    
    39.      }    
    40.      
    41.  @Override    
    42.  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    
    43.          db.execSQL("DROP TABLE IF EXISTS mycontacts");    
    44.          onCreate(db);    
    45.      }    
    46.  public boolean addStudentContact(String contactname,String contactphone,String contactstreet,String contactemail, String contactplace){    
    47.  /*,*/    
    48.  SQLiteDatabase db=this.getWritableDatabase();    
    49.          ContentValues contantValues = new ContentValues();    
    50.          contantValues.put("name",contactname);    
    51.          contantValues.put("phone", contactphone);    
    52.          contantValues.put("street",contactstreet);    
    53.          contantValues.put("email",contactemail);    
    54.          contantValues.put("place",contactplace);    
    55.          db.insert("mycontacts"null, contantValues);    
    56.          db.close();    
    57.  return true;    
    58.      }    
    59.  public boolean updateStudentContact(Integer contactid,String contactname,String contactphone,String contactstreet,String contactemail, String contactplace)    
    60.      {    
    61.  /*,String contactname,*/    
    62.  SQLiteDatabase db=this.getWritableDatabase();    
    63.          ContentValues contantValues = new ContentValues();    
    64.          contantValues.put("name",contactname);    
    65.          contantValues.put("phone", contactphone);    
    66.          contantValues.put("street",contactstreet);    
    67.          contantValues.put("email",contactemail);    
    68.          contantValues.put("place",contactplace);    
    69.          db.update("mycontacts", contantValues, "id = ?"new String[]{Integer.toString(contactid)});    
    70.          db.close();    
    71.  return true;    
    72.      }    
    73.  public Integer deleteContact(Integer id){    
    74.          SQLiteDatabase db=this.getWritableDatabase();    
    75.  return db.delete("mycontacts","id = ?",new String[]{Integer.toString(id)});    
    76.      }    
    77.  public Cursor getData(int contactid){    
    78.          SQLiteDatabase db=this.getWritableDatabase();    
    79.          Cursor res=db.rawQuery("Select * from mycontacts where id = " + contactid + ""null);    
    80.  return res;    
    81.      }    
    82.  public int numberOfRows(){    
    83.          SQLiteDatabase db=this.getWritableDatabase();    
    84.  int numRows=(int) DatabaseUtils.queryNumEntries(db,CONTACTS_TABLE_NAME);    
    85.  return numRows;    
    86.      }    
    87.  public ArrayList<String> getAllStudentContacts(){    
    88.          ArrayList<String> arraylist= new ArrayList<String>();    
    89.          SQLiteDatabase db=this.getReadableDatabase();    
    90.          Cursor cursor=db.rawQuery("Select * from mycontacts",null);    
    91.      
    92.  if (cursor.moveToFirst()) {    
    93.  do {    
    94.                  arraylist.add(cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_STUNAME)));    
    95.   } while (cursor.moveToNext());    
    96.          }    
    97.  return arraylist;    
    98.      }    
    99.  }    
      Add another java class called DisplayContact.java. Add controls to add and display a student detail like name, place, email, phone and city.
      1. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    
      2.  xmlns:tools="http://schemas.android.com/tools"    
      3.  android:layout_width="match_parent"    
      4.  android:layout_height="wrap_content"    
      5.  android:id="@+id/scrollView1"    
      6.  >    
      7.      
      8.      <RelativeLayout    
      9.  android:layout_width="match_parent"    
      10.  android:layout_height="350dp"    
      11.  android:paddingLeft="@dimen/activity_horizontal_margin"    
      12.  android:paddingRight="@dimen/activity_horizontal_margin"    
      13.  android:paddingTop="@dimen/activity_vertical_margin"    
      14.  android:paddingBottom="@dimen/activity_vertical_margin"    
      15.  tools:context="com.test.ppandey.contactapp.DisplayContact">    
      16.      
      17.          <EditText    
      18.  android:id="@+id/editTextName"    
      19.  android:layout_width="wrap_content"    
      20.  android:layout_height="wrap_content"    
      21.  android:layout_alignParentLeft="true"    
      22.  android:layout_marginTop="5dp"    
      23.  android:layout_marginLeft="82dp"    
      24.  android:ems="10"    
      25.  android:inputType="text" >    
      26.          </EditText>    
      27.      
      28.          <EditText    
      29.  android:id="@+id/editTextEmail"    
      30.  android:layout_width="wrap_content"    
      31.  android:layout_height="wrap_content"    
      32.  android:layout_alignLeft="@+id/editTextStreet"    
      33.  android:layout_below="@+id/editTextStreet"    
      34.  android:layout_marginTop="22dp"    
      35.  android:ems="10"    
      36.  android:inputType="textEmailAddress" />    
      37.      
      38.          <TextView    
      39.  android:id="@+id/textView1"    
      40.  android:layout_width="wrap_content"    
      41.  android:layout_height="wrap_content"    
      42.  android:layout_alignBottom="@+id/editTextName"    
      43.  android:layout_alignParentLeft="true"    
      44.  android:text="@string/name"    
      45.  android:textAppearance="?android:attr/textAppearanceMedium" />    
      46.      
      47.          <Button    
      48.  android:id="@+id/button1"    
      49.  android:layout_width="wrap_content"    
      50.  android:layout_height="wrap_content"    
      51.  android:layout_alignLeft="@+id/editTextCity"    
      52.  android:layout_alignParentBottom="true"    
      53.  android:layout_marginBottom="28dp"    
      54.  android:onClick="saveData"    
      55.  android:text="@string/save" />    
      56.      
      57.          <TextView    
      58.  android:id="@+id/textView2"    
      59.  android:layout_width="wrap_content"    
      60.  android:layout_height="wrap_content"    
      61.  android:layout_alignBottom="@+id/editTextEmail"    
      62.  android:layout_alignLeft="@+id/textView1"    
      63.  android:text="@string/email"    
      64.  android:textAppearance="?android:attr/textAppearanceMedium" />    
      65.      
      66.          <TextView    
      67.  android:id="@+id/textView5"    
      68.  android:layout_width="wrap_content"    
      69.  android:layout_height="wrap_content"    
      70.  android:layout_alignBottom="@+id/editTextPhone"    
      71.  android:layout_alignLeft="@+id/textView1"    
      72.  android:text="@string/phone"    
      73.  android:textAppearance="?android:attr/textAppearanceMedium" />    
      74.      
      75.          <TextView    
      76.  android:id="@+id/textView4"    
      77.  android:layout_width="wrap_content"    
      78.  android:layout_height="wrap_content"    
      79.  android:layout_above="@+id/editTextEmail"    
      80.  android:layout_alignLeft="@+id/textView5"    
      81.  android:text="@string/street"    
      82.  android:textAppearance="?android:attr/textAppearanceMedium" />    
      83.      
      84.          <EditText    
      85.  android:id="@+id/editTextCity"    
      86.  android:layout_width="wrap_content"    
      87.  android:layout_height="wrap_content"    
      88.  android:layout_alignRight="@+id/editTextName"    
      89.  android:layout_below="@+id/editTextEmail"    
      90.  android:layout_marginTop="30dp"    
      91.  android:ems="10"    
      92.  android:inputType="text" />    
      93.      
      94.          <TextView    
      95.  android:id="@+id/textView3"    
      96.  android:layout_width="wrap_content"    
      97.  android:layout_height="wrap_content"    
      98.  android:layout_alignBaseline="@+id/editTextCity"    
      99.  android:layout_alignBottom="@+id/editTextCity"    
      100.  android:layout_alignParentLeft="true"    
      101.  android:layout_toLeftOf="@+id/editTextEmail"    
      102.  android:text="@string/country"    
      103.  android:textAppearance="?android:attr/textAppearanceMedium" />    
      104.      
      105.          <EditText    
      106.  android:id="@+id/editTextStreet"    
      107.  android:layout_width="wrap_content"    
      108.  android:layout_height="wrap_content"    
      109.  android:layout_alignLeft="@+id/editTextName"    
      110.  android:layout_below="@+id/editTextPhone"    
      111.  android:ems="10"    
      112.  android:inputType="text" >    
      113.      
      114.              <requestFocus />    
      115.          </EditText>    
      116.      
      117.          <EditText    
      118.  android:id="@+id/editTextPhone"    
      119.  android:layout_width="wrap_content"    
      120.  android:layout_height="wrap_content"    
      121.  android:layout_alignLeft="@+id/editTextStreet"    
      122.  android:layout_below="@+id/editTextName"    
      123.  android:ems="10"    
      124.  android:inputType="phone|text" />    
      125.      
      126.      </RelativeLayout>    
      127.  </ScrollView>   
        Implement some methods to add, update and delete student information in DisplayContact.java class file.
        1. package com.test.ppandey.contactapp;    
        2.      
        3.  import android.app.AlertDialog;    
        4.  import android.content.DialogInterface;    
        5.  import android.content.Intent;    
        6.  import android.database.Cursor;    
        7.  import android.support.v7.app.ActionBarActivity;    
        8.  import android.os.Bundle;    
        9.  import android.view.Menu;    
        10.  import android.view.MenuItem;    
        11.  import android.view.View;    
        12.  import android.widget.Button;    
        13.  import android.widget.TextView;    
        14.  import android.widget.Toast;    
        15.      
        16.  public class DisplayContact extends ActionBarActivity {    
        17.  int from_Where_I_Am_Coming = 0;    
        18.  private DBHelper mydb;    
        19.      TextView name;    
        20.      TextView phone;    
        21.      TextView email;    
        22.      TextView street;    
        23.      TextView place;    
        24.  int id_To_Update = 0;    
        25.      
        26.  @Override    
        27.  protected void onCreate(Bundle savedInstanceState) {    
        28.  super.onCreate(savedInstanceState);    
        29.          setContentView(R.layout.activity_display_contact);    
        30.      
        31.  name = (TextView) findViewById(R.id.editTextName);    
        32.  phone = (TextView) findViewById(R.id.editTextPhone);    
        33.  email = (TextView) findViewById(R.id.editTextStreet);    
        34.  street = (TextView) findViewById(R.id.editTextEmail);    
        35.  place = (TextView) findViewById(R.id.editTextCity);    
        36.      
        37.  mydb = new DBHelper(this);    
        38.      
        39.          Bundle extras = getIntent().getExtras();    
        40.          {    
        41.  int Value = extras.getInt("id");    
        42.      
        43.  if (Value > 0) {    
        44.  //means this is the view part not the add contact part.    
        45.  Cursor rs = mydb.getData(Value);    
        46.  id_To_Update = Value;    
        47.                  rs.moveToFirst();    
        48.      
        49.                  String stuname = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUNAME));    
        50.                  String stuphone = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUPHONE));    
        51.                  String stuemail = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUEMAIL));    
        52.                  String stustreet = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUSTREET));    
        53.                  String stuplace = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STUCITY));    
        54.      
        55.  if (!rs.isClosed()) {    
        56.                      rs.close();    
        57.                  }    
        58.                  Button b = (Button) findViewById(R.id.button1);    
        59.                  b.setVisibility(View.INVISIBLE);    
        60.      
        61.  name.setText((CharSequence) stuname);    
        62.  name.setFocusable(false);    
        63.  name.setClickable(false);    
        64.      
        65.  phone.setText((CharSequence) stuphone);    
        66.  phone.setFocusable(false);    
        67.  phone.setClickable(false);    
        68.      
        69.  email.setText((CharSequence) stuemail);    
        70.  email.setFocusable(false);    
        71.  email.setClickable(false);    
        72.      
        73.  street.setText((CharSequence) stustreet);    
        74.  street.setFocusable(false);    
        75.  street.setClickable(false);    
        76.      
        77.  place.setText((CharSequence) stuplace);    
        78.  place.setFocusable(false);    
        79.  place.setClickable(false);    
        80.              }    
        81.          }    
        82.      }    
        83.      
        84.  @Override    
        85.  public boolean onCreateOptionsMenu(Menu menu) {    
        86.  // Inflate the menu; this adds items to the action bar if it is present.    
        87.  Bundle extras = getIntent().getExtras();    
        88.      
        89.  if (extras != null) {    
        90.  int Value = extras.getInt("id");    
        91.  if (Value > 0) {    
        92.                  getMenuInflater().inflate(R.menu.menu_display_contact, menu);    
        93.              } else {    
        94.                  getMenuInflater().inflate(R.menu.menu_main, menu);    
        95.              }    
        96.          }    
        97.  return true;    
        98.      }    
        99.      
        100.  @Override    
        101.  public boolean onOptionsItemSelected(MenuItem item) {    
        102.  // Handle action bar item clicks here. The action bar will    
        103.          // automatically handle clicks on the Home/Up button, so long    
        104.          // as you specify a parent activity in AndroidManifest.xml.    
        105.  super.onOptionsItemSelected(item);    
        106.  switch (item.getItemId()) {    
        107.  case R.id.Edit_Contact:    
        108.                  Button b = (Button) findViewById(R.id.button1);    
        109.                  b.setVisibility(View.VISIBLE);    
        110.  name.setEnabled(true);    
        111.  name.setFocusableInTouchMode(true);    
        112.  name.setClickable(true);    
        113.      
        114.  phone.setEnabled(true);    
        115.  phone.setFocusableInTouchMode(true);    
        116.  phone.setClickable(true);    
        117.      
        118.  email.setEnabled(true);    
        119.  email.setFocusableInTouchMode(true);    
        120.  email.setClickable(true);    
        121.      
        122.  street.setEnabled(true);    
        123.  street.setFocusableInTouchMode(true);    
        124.  street.setClickable(true);    
        125.      
        126.  place.setEnabled(true);    
        127.  place.setFocusableInTouchMode(true);    
        128.  place.setClickable(true);    
        129.      
        130.  return true;    
        131.  case R.id.Delete_Contact:    
        132.      
        133.                  AlertDialog.Builder builder = new AlertDialog.Builder(this);    
        134.                  builder.setMessage(R.string.deleteContact)    
        135.                          .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {    
        136.  public void onClick(DialogInterface dialog, int id) {    
        137.  mydb.deleteContact(id_To_Update);    
        138.                                  Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();    
        139.                                  Intent intent = new Intent(getApplicationContext(), MainActivity.class);    
        140.                                  startActivity(intent);    
        141.                              }    
        142.                          })    
        143.                          .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {    
        144.  public void onClick(DialogInterface dialog, int id) {    
        145.  // User cancelled the dialog    
        146.  }    
        147.                          });    
        148.                  AlertDialog d = builder.create();    
        149.                  d.setTitle("Are you sure ?");    
        150.                  d.show();    
        151.      
        152.  return true;    
        153.  default:    
        154.  return super.onOptionsItemSelected(item);    
        155.      
        156.          }    
        157.      }    
        158.      
        159.  public void saveData(View view) {    
        160.  /*, */    
        161.  /*        mydb.addContact(name.getText().toString(),email.getText().toString(), street.getText().toString(), place.getText().toString(), phone.getText().toString());  
        162.          finish();*/    
        163.  Bundle extras = getIntent().getExtras();    
        164.  if (extras != null) {    
        165.  int Value = extras.getInt("id");    
        166.  if (Value > 0) {    
        167.  if (mydb.updateStudentContact(id_To_Update, name.getText().toString(), phone.getText().toString(), street.getText().toString(),email.getText().toString(), place.getText().toString())) {    
        168.                      Toast.makeText(getApplicationContext(), "Successfully Updated", Toast.LENGTH_SHORT).show();    
        169.                      Intent intent = new Intent(getApplicationContext(), MainActivity.class);    
        170.                      startActivity(intent);    
        171.                  } else {    
        172.                      Toast.makeText(getApplicationContext(), "Record not updated", Toast.LENGTH_SHORT).show();    
        173.                  }    
        174.              } else {    
        175.  if (mydb.addStudentContact(name.getText().toString(), phone.getText().toString(),street.getText().toString(), email.getText().toString(),  place.getText().toString())) {    
        176.                      Toast.makeText(getApplicationContext(), "Successfully Added", Toast.LENGTH_SHORT).show();    
        177.                  } else {    
        178.                      Toast.makeText(getApplicationContext(), "Record not added", Toast.LENGTH_SHORT).show();    
        179.                  }    
        180.                  Intent intent = new Intent(getApplicationContext(), MainActivity.class);    
        181.                  startActivity(intent);    
        182.              }    
        183.          }    
        184.      }    
        185.  }   
          Added strings.xml file in values folder and add the following code.
          1. <?xml version="1.0" encoding="utf-8"?>    
          2.  <resources>    
          3.      <string name="app_name">ContactApp</string>    
          4.      
          5.      <string name="hello_world">Hello world!</string>    
          6.      <string name="action_settings">Settings</string>    
          7.      <string name="title_activity_display_contact">DisplayContact</string>    
          8.      <string name="Add_New">Add New</string>    
          9.      <string name="edit">Edit Contact</string>    
          10.      <string name="delete">Delete Contact</string>    
          11.      <string name="name">Name</string>    
          12.      <string name="phone">Phone</string>    
          13.      <string name="email">Email</string>    
          14.      <string name="street">Street</string>    
          15.      <string name="country">City/State/Zip</string>    
          16.      <string name="save">Save Contact</string>    
          17.      <string name="deleteContact">Are you sure, you want to delete it.</string>    
          18.      <string name="yes">Yes</string>    
          19.      <string name="no">No</string>    
          20.  </resources>   
          In MainActivity.java class, first, create an object of DBHelper class. Using the getAllStudentContacts method, bind the listview objects with the student name.
           
          Build the application and run the app.
           
           
          Click on the right top to add new student information.
           
           
          Fill the student information.
           
           
          Student information is saved.
           
           
          If you want to update student information, select one student from the list. Student information will be opened and right-click on the edit option to edit the student information and save the data.
           
           
          Similarly, if you want to delete any record, select that student from the list and click on delete option on the right top to delete the student.
           
          So, now we can see the database using Android Device Monitor.
           
           
          Click on the red shaded icon to push the database. Save it in a folder.

          Open the SQLite browser to open the database.

           
           

          Summary

           
          I hope you enjoyed creating a CRUD application in Android Studio.


          Similar Articles