SQLite Android Tutorial – Easy

SQLite Android Tutorial

Hello every one, welcome back again. Main perspective of this article is about to know basics of SQLite database programming of Android. Inside this SQLite Android Tutorial, i have talked how you can work with SQLite database to create, update and fetch details by creating an android application.

Introduction

SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don’t need to establish any kind of connections for it like JDBC,ODBC e.t.c. Developer widely use this light weight database in their Android Applications. Lets start with the Tutorial,

Before starting you have to be ready with Entities of your database. Let’s say ‘Student’. In this program i am about to build application in which we can easily add and modify student details & all the information will be stored in SQLite database.

APP CODING:

The objective of our application is to store student details in our Application which we can update later if we want. So for this, we require to create a class named Student (Entity Name : Student) with parameters (Fields of entity), (id, enrollNo, name, phoneNumber). We require one empty constructor as well as two parameterized constructor as shown in below code snppet. As you can see we also require getters and setters for each parameter of our class.

Student.java

package com.purvik.studinfo;

/**
 *
 * Purvik Rana - Student Main Class
 * Attributes: id, enroll_no, name, phone_number;
 * Constructor: empty, all parameter, three parameter
 * Getter & Setters: all attributes
 */
public class Student {

    //Private Variable
    int _id;
    int _enroll_no;
    String _name;
    String _phone_number;

    //empty constructor
    public Student() {
    }

    //all parameter in Constructor
    public Student(int _id, String _name, int _enroll_no, String _phone_number) {
        this._id = _id;
        this._name = _name;
        this._enroll_no = _enroll_no;
        this._phone_number = _phone_number;
    }

    //three parameter Constructor
    public Student(int _enroll_no, String _name, String _phone_number) {
        this._enroll_no = _enroll_no;
        this._name = _name;
        this._phone_number = _phone_number;
    }


    //Getters for  all fields
    public int get_id() {
        return _id;
    }

    public int get_enroll_no() {
        return _enroll_no;
    }

    public String get_name() {
        return _name;
    }

    public String get_phone_number() {
        return _phone_number;
    }

    //Setters for all fields
    public void set_id(int _id) {
        this._id = _id;
    }

    public void set_enroll_no(int _enroll_no) {
        this._enroll_no = _enroll_no;
    }

    public void set_name(String _name) {
        this._name = _name;
    }

    public void set_phone_number(String _phone_number) {
        this._phone_number = _phone_number;
    }
}

So far, this is the class what we require to build. Now next create DBHandler class that will handle Database operations between our applications and database as displayed in code snippet below. That will make use of parameters and fields of previous created class that is Student.java.

DBHandler.java

package com.purvik.studinfo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class DBHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "student";

    // Contacts table name
    private static final String TABLE_STUDENT_DETAIL = "studentDetails";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_ENROLL_NO = "enroll_no";
    private static final String KEY_NAME = "name";
    private static final String KEY_PHONE_NO = "phone_number";

    public DBHandler(Context contex) {
        super(contex, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_STUDENT_DETAIL_TABLE = "CREATE TABLE " + TABLE_STUDENT_DETAIL + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_ENROLL_NO + " TEXT,"
                + KEY_NAME + " TEXT,"
                + KEY_PHONE_NO + " TEXT " + ")";

        db.execSQL(CREATE_STUDENT_DETAIL_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENT_DETAIL);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new Student Information
    void addNewStudent(Student newStud) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_ENROLL_NO, newStud.get_enroll_no());
        values.put(KEY_NAME, newStud.get_name());
        values.put(KEY_PHONE_NO, newStud.get_phone_number());


        // Inserting Row
        db.insert(TABLE_STUDENT_DETAIL, null, values);
        db.close(); // Closing database connection
    }


    public boolean updateStudentInfo(int updId, int updEnrolNo, String updName, String updPhoneNo) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues args = new ContentValues();

        args.put(KEY_ENROLL_NO, updEnrolNo);
        args.put(KEY_NAME, updName);
        args.put(KEY_PHONE_NO, updPhoneNo);

        return db.update(TABLE_STUDENT_DETAIL, args, KEY_ID + "=" + updId, null) > 0;
    }



    // Getting All Students
    public List<Student> getAllStudentList() {


        List<Student> studentList = new ArrayList<Student>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_STUDENT_DETAIL;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {

                Student stdnt = new Student();
                stdnt.set_id(Integer.parseInt(cursor.getString(0)));
                stdnt.set_enroll_no(Integer.parseInt(cursor.getString(1)));
                stdnt.set_name(cursor.getString(2));
                stdnt.set_phone_number(cursor.getString(3));

                // Adding contact to list
                studentList.add(stdnt);

            } while (cursor.moveToNext());
        }

        // return contact list
        return studentList;
    }
}

DBHandler file contain details about our Database Version, Database Name, Table Name, Columns Names (fields) with constructor where we have to pass Database Name and Version as parameters. The main thing is that , we have to extends this class by Baseclass SQLiteOpenHelper, so we can use unimplemented method onCreate and onUpgrade of it. The onCreate() method creates Table with specified name with SQL query. The same for table upgrade is implemented inside onUpgrade() mehod.

The additional three methods addNewStudent, updateStudentInfo, getAllAtudentList are implemented to perform Student creation, updation and list all student respectively. See the code snippet as well it described very well.

Next, We will create layout of our activity where user interact with specific options. See code snippet below,

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/app_main_label"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/in_between_layout_space"
        android:id="@+id/linearLayout">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/btn_label_Add_Student"
            android:id="@+id/btnAddStudent" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/btn_label_Show_Details"
            android:id="@+id/btnShowDetails" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/btn_label_Update_Details"
            android:id="@+id/btnUpdateInfo" />
    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/tvStdList"
        android:layout_below="@+id/linearLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/in_between_layout_space"
        android:gravity="center_horizontal" />
</RelativeLayout>

As you can see, we have put three buttons to perform operations that we have already specified in DBHandler class. For each operation we have to specify a method in our MainActivity.java file. So see the code snippet below,

MainActivity.java

package com.purvik.studinfo;

import android.app.DialogFragment;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ArrowKeyMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.nio.LongBuffer;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AddStudentDialog.AddStudentDialogListener,
                                UpdateStudentInfo.UpdateStudentDialogListener {

    Button btnAddStudent, btnUpdateInfo, btnShowDetails;
    TextView tvStdInfo;
    private String TAG = "StudInfo";
    SQLiteDatabase dtb;
    DBHandler db;


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

        db = new DBHandler(this);

        btnAddStudent = (Button)findViewById(R.id.btnAddStudent);
        btnShowDetails = (Button)findViewById(R.id.btnShowDetails);
        btnUpdateInfo = (Button)findViewById(R.id.btnUpdateInfo);

        btnAddStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AddStudentDialog dialog = new AddStudentDialog();
                dialog.show(getFragmentManager(), TAG);
            }
        });

        btnUpdateInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateStudentInfo updateDialog = new UpdateStudentInfo();
                updateDialog.show(getFragmentManager(),TAG);
            }
        });


        btnShowDetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //View Block Number List in the Text View Widget
                tvStdInfo = (TextView) findViewById(R.id.tvStdList);

                tvStdInfo.setMovementMethod(ArrowKeyMovementMethod.getInstance());

                tvStdInfo.setText("");    //    clear text area at each button press
                tvStdInfo.setTextColor(Color.MAGENTA);
                tvStdInfo.setPadding(5, 2, 5, 2);

                List<Student> studentsList = db.getAllStudentList();	//	fetch List of BlockedNumbers form DB  method - 'getAllBlockedNumbers'

                for (Student std : studentsList) {

                    String stdDetail = "\n\nID:" + std.get_id()+ "\n\tENO:" + std.get_enroll_no() +"\n\tNAME:" + std.get_name() + "\n\tPHN NO:"+ std.get_phone_number();
                    tvStdInfo.append("\n"+ stdDetail);

                    //	Log.i("TAG", log);
                }
            }
        });




    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveButtonClick(DialogFragment dialog) {

        //		Get enrollNumber
        EditText entEnrolNo = (EditText) dialog.getDialog().findViewById(R.id.edtEnrollNo);
        String enrollNo = entEnrolNo.getText().toString();
        int int_enrollNo =Integer.parseInt(entEnrolNo.getText().toString());


//		Get Name
        EditText entName = (EditText) dialog.getDialog().findViewById(R.id.edtName);
        String name = entName.getText().toString();

        //		Get Phone Number
        EditText entPhnNo = (EditText) dialog.getDialog().findViewById(R.id.edtPhoneNo);
        String  phnNo = entPhnNo.getText().toString();



        boolean check_enrollNo = checkEnrollNo(enrollNo);

        boolean check_name = checkName(name);

        boolean check_phnNo = checkPhoneNo(phnNo);

        if(check_enrollNo == false || check_name == false || check_phnNo == false){

            Toast.makeText(getApplicationContext(),"Enter Data Again.. :P",Toast.LENGTH_LONG).show();
        }else{

            db.addNewStudent(new Student(int_enrollNo,name,phnNo));

            Toast.makeText(getApplicationContext(),"Student Added to the List.. O_o",Toast.LENGTH_LONG).show();
        }



        Toast.makeText(getApplicationContext(),"\nNo :" + enrollNo + "\nName: " + name + "\nPhone No:" + phnNo,Toast.LENGTH_LONG).show();



    }

    //Check Id Number
    public boolean checkIdno(String Id_No){

        if(Id_No == ""){
            return false;
        }else{
            return true;
        }

    }

    //Check Enrollment number
    public boolean checkEnrollNo(String enr_No){

        if(enr_No == "" || enr_No.length() != 3){

            return false;
        }else{
            return true;
        }

    }

    //Check Name
    public boolean checkName(String stdName){

        if(stdName == ""){
            return false;
        }else{
            return true;
        }
    }

    //Check Phone Number
    public boolean checkPhoneNo(String phn_No){

        if(phn_No == "" || phn_No.length() != 10){

            return false;
        }else{
            return true;
        }

    }

    @Override
    public void onUpdateButtonClick(DialogFragment dialog) {


//		Get enrollNumber
        EditText entId = (EditText) dialog.getDialog().findViewById(R.id.edt_UpdateId);
        String idNo = entId.getText().toString();
        int int_idNo =Integer.parseInt(entId.getText().toString());

        //		Get enrollNumber
        EditText entEnrolNo = (EditText) dialog.getDialog().findViewById(R.id.edt_UpdateEnrollNo);
        String enrollNo = entEnrolNo.getText().toString();
        int int_enrollNo =Integer.parseInt(entEnrolNo.getText().toString());


//		Get Name
        EditText entName = (EditText) dialog.getDialog().findViewById(R.id.edt_UpdateName);
        String name = entName.getText().toString();

        //		Get Phone Number
        EditText entPhnNo = (EditText) dialog.getDialog().findViewById(R.id.edt_UpdatePhoneNo);
        String  phnNo = entPhnNo.getText().toString();

        boolean check_idNo = checkIdno(idNo);

        boolean check_enrollNo = checkEnrollNo(enrollNo);

        boolean check_name = checkName(name);

        boolean check_phnNo = checkPhoneNo(phnNo);

        if(check_idNo == false  || check_enrollNo == false || check_name == false || check_phnNo == false){

            Toast.makeText(getApplicationContext(),"Enter Data Again.. :P",Toast.LENGTH_LONG).show();
        }else{

            boolean updateCheck = db.updateStudentInfo(int_idNo, int_enrollNo, name, phnNo);

            if(updateCheck == true){

            Toast.makeText(getApplicationContext(),"Student Added to the List.. O_o",Toast.LENGTH_LONG).show();}
            else{

                Toast.makeText(getApplicationContext(),"Details Updation Failes.. :(",Toast.LENGTH_LONG).show();
            }
        }
    }
}

Each button click will pop up an alert dialog that will ask user to input few fields according to its requirement. The xml and java for this Alert dialog is as below:

student_form.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView2"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/in_between_widget_space"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/tv_enrollNO"
        android:id="@+id/textView4"
        android:layout_marginTop="@dimen/in_between_widget_space"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberSigned"
        android:ems="10"
        android:id="@+id/edtEnrollNo" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/tv_Name"
        android:id="@+id/textView3"
        android:layout_marginTop="@dimen/in_between_widget_space"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/edtName" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/tv_Phone_Np"
        android:id="@+id/textView5"
        android:layout_marginTop="@dimen/in_between_widget_space" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/edtPhoneNo" />

</LinearLayout>

AddStudentDialog.java

package com.purvik.studinfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;

/**
 * Created by 3537 
 */
public class AddStudentDialog extends DialogFragment {

    ////interface to handle the Events
    interface AddStudentDialogListener{

        void onSaveButtonClick(DialogFragment dialog);
        //void onCancelButtonClick(DialogFragment dialog);

    }

    //create an Instance to deliever the action
    AddStudentDialogListener addStudentListener;
    Context context;

    // Override the Fragment.onAttach() method to instantiate the SetPasswordDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the SetPasswordDialogListener so we can send events to the host
            addStudentListener = (AddStudentDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement AddStudentDialogListener");
        }
    }
    //END

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.student_form, null))

                // Add action buttons
                .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        addStudentListener.onSaveButtonClick(AddStudentDialog.this);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        AddStudentDialog.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }
}

udpate_student_info.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/updateForm_Title"
        android:id="@+id/textView6"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView6"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/in_between_layout_space">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/tv_Id"
            android:id="@+id/textView10"
            android:layout_marginTop="@dimen/in_between_widget_space"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/edt_UpdateId" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/tv_enrollNO"
            android:id="@+id/textView7"
            android:layout_marginTop="@dimen/in_between_widget_space"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:id="@+id/edt_UpdateEnrollNo" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/tv_Name"
            android:id="@+id/textView8"
            android:layout_marginTop="@dimen/in_between_widget_space"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/edt_UpdateName" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/tv_Phone_Np"
            android:id="@+id/textView9"
            android:layout_marginTop="@dimen/in_between_widget_space"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="phone"
            android:ems="10"
            android:id="@+id/edt_UpdatePhoneNo" />
    </LinearLayout>
</RelativeLayout>

UpdateStudentInfo.java

package com.purvik.studinfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;

/**
 * Created by 3537 
 */
public class UpdateStudentInfo extends DialogFragment {

    ////interface to handle the Events
    interface UpdateStudentDialogListener{

        void onUpdateButtonClick(DialogFragment dialog);
        //void onCancelButtonClick(DialogFragment dialog);

    }

    //create an Instance to deliever the action
    UpdateStudentDialogListener updateStudentListener;
    Context context;

    // Override the Fragment.onAttach() method to instantiate the SetPasswordDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the SetPasswordDialogListener so we can send events to the host
            updateStudentListener = (UpdateStudentDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement UpdateStudentDialogListener");
        }
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.udpate_student_info, null))

                // Add action buttons
                .setPositiveButton(R.string.tv_Update, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        updateStudentListener.onUpdateButtonClick(UpdateStudentInfo.this);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        UpdateStudentInfo.this.getDialog().cancel();
                    }
                });
        return builder.create();

    }
}

JAVA files use to create dialog and display it as specified in respective XML files. In these JAVA files we have also defined the interface that we have implemented in MainActivity.java file. The method implemented in MainActivity.java file handles actual transaction of adding and modifying student data in the database after proper validation.

There is no  other activity that we have created in this application so no need to alter AndroidManifest.xml file.

it is as,

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.purvik.studinfo" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

String resources that we have used in this application is as below,

Strings.xml

<resources>
    <string name="app_name">StudInfo</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="app_main_label">StudInfo</string>
    <string name="btn_label_Add_Student">Add Student</string>
    <string name="btn_label_Show_Details">Show Details</string>
    <string name="btn_label_Update_Details">Update Info</string>
    <string name="tv_Name">Name</string>
    <string name="tv_enrollNO">Enroll No</string>
    <string name="tv_Phone_Np">Phone No</string>
    <string name="add">ADD</string>
    <string name="cancel">CANCEL</string>
    <string name="updateForm_Title">UPDATE INFO</string>
    <string name="tv_Id">ID</string>
    <string name="tv_Update">UPDATE</string>

</resources>

So till now all the programming part is ready with all file configurations. Just add the files as specified in all code snippets above with respective names.

Just execute application, you will see how it is working and performing all the operations. Snaps are as below,

SQLite Android Tutorial

Home Screen

SQLite Android Tutorial

Add Student

SQLite Android Tutorial

Show Details

SQLite Android Tutorial

Updated Details

So this is how application that we have just implemented will work. If you stuck in between somewhere, you can always ping me your queries as comments. I’ll be happy to resolve your queries.

“Bless for You, Peace for the World” – Purvik Rana

Leave a Reply

Your email address will not be published. Required fields are marked *