What is SQLite?

SQLite is a relational database which is used to perform all database operation such as storing and manipulating data to or from the database. SQLite is embedded with Android, it means it is a built in feature of Android so there is no need of any external things or extra setup to use SQLite.

Android SQLite Database Example

In this Android SQLite Database tutorial we are going to learn how to perform SQL task in SQLite such as creating database, creating tables, inserting, updating, deleting and retrieving records to and from SQLite database.

Before starting this please refer my previous blog ListView in Android using Custom Adapter because I have implemented ListView in this blog to retrieve records from database.

Create Android Project

Step 1. Create Android Project with an empty Activity called MainActivity. As we have created Activity, two files activity_main.xml and MainActivity.java will be created in its correspondent folders. See project structure given at end of this blog. I have created project with name SQLiteDatabase.

Create SQLite OpenHelper class

To perform SQL operation such as Insert, Update, Delete and Select Android have built in class SQLiteOpenHelper. To use feature of this class we have to extends SQLiteOpenHelper class.

Step 1. Create a class named DbHelper.java and extends it from SQLiteOpenHelper. This class will contain methods to perform Insert, Update, Delete and Select operation with database.

Step to create java file: Right click to “com.example.sqlitedatabaseconnectivity” inside java folder -> New -> Java Class -> Write name (DbHelper) ->OK.

Note: When you extends DbHelper class from SQLiteOpenHelper it will show red line below it. It can be solved by implementing its methods and its constructor. Just use Alt+Enter to implement its methods and constructor. When you press Alt+Enter you will see one dialogue box with onCreate() and onUpgrade() method. Click OK to implement both. Again press Alt+Enter to implement its constructor. Select first constructor only.

  • Constructor will call when object of this class is created. Constructor takes four arguments. First is Context i.e Activity, Second is Database Name, Third is Cursor which is optional and forth is Database Version.

public static String DatabaseName = "app.db";

public static int DatabaseVersion = 1;

  

public DbHelper(Context context) {

    super(context, DatabaseName, null, DatabaseVersion);

}

  • onCreate(SQLiteDatabase db) method will be called only once when the app is installed or the activity with this method called. This method is used to create tables.
  • onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) method will called when update of app is released. You have to change Database Version to execute this method. You can change database version in constructor. Please take care of older records available in database while modifying database. In this example I have dropped older table and recreated it again.

Step 2. Write methods to perform Insert, Update, Delete and Select operation in DbHelper.java class. Below is the code for DbHelper.java class. I have used comments to understand code. You can remove it while utilizing code.

DbHelper.java

package com.example.sqlitedatabaseconnectivity;

  

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

  

public class DbHelper extends SQLiteOpenHelper {

  

    /* Final variables */

    private static final String databaseName = "app.db";

    private static final int databaseVersion = 1;

    private static final String tableName = "tblEmployee";

    private static final String columnEmployeeId = "EmployeeId";

    private static final String columnEmployeeName = "EmployeeName";

    private static final String columnEmployeeSalary = "EmployeeSalary";

  

    /* Constructor of class */

    public DbHelper(Context context) {

        super(context, databaseName, null, databaseVersion);

    }

  

    /* Override method onCreate() which used to create tables */

    @Override

    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + "(" + columnEmployeeId + " INTEGER PRIMARY KEY AUTOINCREMENT, " + columnEmployeeName + " TEXT, " + columnEmployeeSalary + " TEXT)");

    }

  

    /* Override method onUpgrade() which used to modify database when version changes */

    @Override

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

        db.execSQL("DROP TABLE IF EXISTS " + tableName);

        onCreate(db);

    }

  

    /* Insert method */

    public long fnInsert(String _eName, String _eSalary) {

  

        SQLiteDatabase db = this.getWritableDatabase(); /* Taking database in writable mode */

  

        ContentValues cv = new ContentValues(); /* ContentValues class used to define column names and its value to be insert */

        cv.put(columnEmployeeName, _eName);

        cv.put(columnEmployeeSalary, _eSalary);

  

        long returnValue = db.insert(tableName, null, cv); /* db.insert() method will insert record in database and return long value */

  

        return returnValue;

  

    }

  

    /* Select method */

    public Cursor fnSelect() {

  

        SQLiteDatabase db = this.getReadableDatabase(); /* Taking database in readable mode */

        Cursor c = db.rawQuery("SELECT * FROM " + tableName, null); /* Cursor hold records of Select query */

        return c;

  

    }

  

    /* Select method to get records by id fo update or delete */

    public Cursor fnSelectRecordById(int _eId) {

  

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor c = db.rawQuery("SELECT * FROM " + tableName + " WHERE " + columnEmployeeId + " = " + _eId, null);

        return c;

  

    }

  

    /* Update method */

    public int fnUpdate(int _eId, String _eName, String _eSalary) {

  

        SQLiteDatabase db = this.getWritableDatabase();

  

        ContentValues cv = new ContentValues();

        cv.put(columnEmployeeId, _eId);

        cv.put(columnEmployeeName, _eName);

        cv.put(columnEmployeeSalary, _eSalary);

  

        int returnValue = db.update(tableName, cv, columnEmployeeId + " = " + _eId, null); /* db.update() method will modify record in database and return int value */

  

        return returnValue;

  

    }

  

    /* Delete method */

    public int fnDelete(int _eId) {

  

        SQLiteDatabase db = this.getWritableDatabase();

        int returnValue = db.delete(tableName, columnEmployeeId + " = " + _eId, null); /* db.delete() method will delete record in database and return int value */

        return returnValue;

  

    }

}

Insert operation

Step 1. As we have already created project with MainActivity. We will design and code in this activity for inserting records in database. Open activity_main.xml, modify file according to your requirements. Design User Interface to take input from users. You can check my code given below.

I am inserting employee record i.e Employee Name and Salary. You can add fields according to your requirements.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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:gravity="center_horizontal"

    android:orientation="vertical"

    android:padding="15dp"

    tools:context=".MainActivity">

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="15dp"

        android:text="Add New Employee"

        android:textSize="20dp"

        android:textStyle="bold" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Name"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <EditText

        android:id="@+id/edtInsEmplyeeName"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:hint="Enter Employee Name"

        android:padding="10dp" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Salary"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <EditText

        android:id="@+id/edtInsEmplyeeSalary"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:hint="Enter Employee Salary"

        android:padding="10dp" />

  

    <Button

        android:id="@+id/btnInsAdd"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Add" />

  

    <TextView

        android:id="@+id/txtInsViewEmplyee"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="right"

        android:text="View Employees"

        android:textSize="12dp"

        android:textStyle="bold" />

  

</LinearLayout>

Step 2. Open MainActivity.java, modify file and write below code to perform insert operation. Insert operation will perform on ADD button’s click event. Please read out all the comments which I have mentioned in code to understand it properly.

MainActivity.java

package com.example.sqlitedatabaseconnectivity;

  

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

  

public class MainActivity extends AppCompatActivity {

  

    /* Declare object to store controls of activity_main.xml file */

    EditText edtInsEmplyeeName, edtInsEmplyeeSalary;

    Button btnInsAdd;

    TextView txtInsViewEmplyee;

  

    /* Declare object of DbHelper.java */

    DbHelper dbHelper;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

  

        /* Find controls from activity_main.xml file and intialize it to object */

        edtInsEmplyeeName = (EditText) findViewById(R.id.edtInsEmplyeeName);

        edtInsEmplyeeSalary = (EditText) findViewById(R.id.edtInsEmplyeeSalary);

        btnInsAdd = (Button) findViewById(R.id.btnInsAdd);

  

        /* Intialize object of DbHelper.java */

        dbHelper = new DbHelper(this);

  

        /* Add button click event */

        btnInsAdd.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

  

                /* Getting user entered values from edittext */

                String eName = "", eSalary = "";

                eName = edtInsEmplyeeName.getText().toString();

                eSalary = edtInsEmplyeeSalary.getText().toString();

  

                /* Call fnInsert() of DbHelper.java class and passing values through parameters */

                long returnValue = dbHelper.fnInsert(eName, eSalary);

                if (returnValue != -1) {

                    Toast.makeText(MainActivity.this, "Employee inserted successfully..!!", Toast.LENGTH_SHORT).show();

                } else {

                    Toast.makeText(MainActivity.this, "Try again..!!", Toast.LENGTH_SHORT).show();

                }

            }

        });

  

        /* Finding view employee textview and setting its click event */

        txtInsViewEmplyee = (TextView) findViewById(R.id.txtInsViewEmplyee);

        txtInsViewEmplyee.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent i = new Intent(MainActivity.this, EmployeeList.class);

                startActivity(i);

            }

        });

  

    }

}

Select operation

To perform select operation and to show all records of table I have used ListView with Edit and Delete buttons. To create a ListView please read my previous blog ListView in Android using Custom Adapter. In previous blog ListView bound with static records. So, to bind ListView with database there are little bit changes you need to do. Please follow below steps.

Step 1. Create new activity with name EmployeeList and put ListView in its xml file (activity_employee_list.xml).

Step to create new Activity: Right click to project “app” -> New -> Activity -> Empty Activity -> Provide Name -> Finish.

Step 2. Modify listinterface.xml file according to requirement. I have modified listinterface.xml. I have removed ImageView and set TextView for Employee Id, Name and Salary. As id can’t display to user I have set it’s android:visibility="gone”.

listinterface.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="horizontal">

  

    <LinearLayout

        android:layout_width="0dp"

        android:layout_height="wrap_content"

        android:layout_weight="1"

        android:orientation="vertical"

        android:padding="5dp">

  

        <TextView

            android:id="@+id/txtSelEmployeeId"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:textColor="#000000"

            android:textSize="18dp"

            android:visibility="gone" />

  

        <TextView

            android:id="@+id/txtSelEmployeeName"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Test Employee"

            android:textColor="#000000"

            android:textSize="18dp" />

  

        <TextView

            android:id="@+id/txtSelEmployeeSalary"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="25,000 Rs."

            android:textSize="12dp" />

  

    </LinearLayout>

  

    <Button

        android:id="@+id/btnSelEdit"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Edit" />

  

    <Button

        android:id="@+id/btnSelDelete"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Delete" />

  

</LinearLayout>

Step 3. Modify DataModel.java file accordingly.

DataMode.java

package com.example.sqlitedatabaseconnectivity;

  

public class DataModel {

  

    private int EmployeeId;

    private String EmployeeName = "";

    private String EmployeeSalary = "";

  

    public void setEmployeeId(int _EmployeeId) {

        this.EmployeeId = _EmployeeId;

    }

  

    public int getEmployeeId() {

        return this.EmployeeId;

    }

  

    public void setEmployeeName(String _EmployeeName) {

        this.EmployeeName = _EmployeeName;

    }

  

    public String getEmployeeName() {

        return this.EmployeeName;

    }

  

    public void setEmployeeSalary(String _EmployeeSalary) {

        this.EmployeeSalary = _EmployeeSalary;

    }

  

    public String getEmployeeSalary() {

        return this.EmployeeSalary;

    }

  

}

Step 4. Modify Constructor, getView() method and ViewHolder class of MyCustomAdapter.java file. Change has been written below.

MyCustomAdapter.java

  • Changes of constructor

ArrayList<DataModel> listDataModel = new ArrayList<DataModel>();

LayoutInflater minflate;

Context context;

  

public MyCustomAdapter(ArrayList<DataModel> _listDataModel, Context _context) {

    this.listDataModel = _listDataModel;

    this.minflate = LayoutInflater.from(_context);

    this.context = _context;

}

  • Changes of getView() method

@Override

public View getView(int position, View convertView, ViewGroup viewGroup) {

    final ViewHolder vh;

    DataModel objDataModel = (DataModel) getItem(position);

    if (convertView == null) {

        convertView = minflate.inflate(R.layout.listinterface, null);

        vh = new ViewHolder();

        vh.txtSelEmployeeId = (TextView) convertView.findViewById(R.id.txtSelEmployeeId);

        vh.txtSelEmployeeName = (TextView) convertView.findViewById(R.id.txtSelEmployeeName);

        vh.txtSelEmployeeSalary = (TextView) convertView.findViewById(R.id.txtSelEmployeeSalary);

        vh.btnSelEdit = (Button) convertView.findViewById(R.id.btnSelEdit);

        vh.btnSelDelete = (Button) convertView.findViewById(R.id.btnSelDelete);

        convertView.setTag(vh);

    } else {

        vh = (ViewHolder) convertView.getTag();

    }

    vh.txtSelEmployeeId.setText(String.valueOf(objDataModel.getEmployeeId()));

    vh.txtSelEmployeeName.setText(objDataModel.getEmployeeName().toString());

    vh.txtSelEmployeeSalary.setText(objDataModel.getEmployeeSalary().toString() + " Rs.");

  

    /* Edit button click event */

    vh.btnSelEdit.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            Intent i = new Intent(context, EmployeeUpdate.class);

            i.putExtra("EmployeeId", vh.txtSelEmployeeId.getText().toString()); /* putExtra() used to pass value from one activity to another activity */

            context.startActivity(i);

        }

    });

  

    /* Delete button click event */

    vh.btnSelDelete.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            Intent i = new Intent(context, EmployeeDelete.class);

            i.putExtra("EmployeeId", vh.txtSelEmployeeId.getText().toString()); /* putExtra() used to pass value from one activity to another activity */

            context.startActivity(i);

        }

    });

  

    return convertView;

}

  • Changes of ViewHolder class

public class ViewHolder {

    TextView txtSelEmployeeId, txtSelEmployeeName, txtSelEmployeeSalary;

    Button btnSelEdit, btnSelDelete;

}

Step 5. Now open EmplyeeList activity where we have put ListView. Open its EmployeeList.java file and modify code. Below is the code.

EmployeeList.java

package com.example.sqlitedatabaseconnectivity;

  

import android.database.Cursor;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.ListView;

import java.util.ArrayList;

  

public class EmployeeList extends AppCompatActivity {

  

    /* Declare object of DbHelper.java */

    DbHelper dbHelper;

  

    /* Final variables */

    private static final String columnEmployeeId = "EmployeeId";

    private static final String columnEmployeeName = "EmployeeName";

    private static final String columnEmployeeSalary = "EmployeeSalary";

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_employee_list);

  

        /* Intialize object of DbHelper.java */

        dbHelper = new DbHelper(this);

  

        ArrayList<DataModel> _liDataModel = listArray();

  

        ListView listView1 = (ListView) findViewById(R.id.listViewData);

        listView1.setAdapter(new MyCustomAdapter(_liDataModel, this));

  

    }

  

    public ArrayList<DataModel> listArray() {

  

        ArrayList<DataModel> objList = new ArrayList<DataModel>();

        DataModel dm;

  

        /* Call fnSelect() of DbHelper.java class */

        Cursor c = dbHelper.fnSelect();

  

        if (c != null && c.getCount() > 0) {

            while (c.moveToNext()) {

                dm = new DataModel();

                dm.setEmployeeId(c.getInt(c.getColumnIndex(columnEmployeeId)));

                dm.setEmployeeName(c.getString(c.getColumnIndex(columnEmployeeName)));

                dm.setEmployeeSalary(c.getString(c.getColumnIndex(columnEmployeeSalary)));

                objList.add(dm);

            }

        }

        return objList;

    }

}

Update operation

Step 1. Create new activity with name EmployeeUpdate to perform update operation.

Step 2. Modify its activity_employee_update.xml file according to requirement. Below is my code for xml file.

activity_employee_update.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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:gravity="center_horizontal"

    android:orientation="vertical"

    android:padding="15dp"

    tools:context=".EmployeeUpdate">

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="15dp"

        android:text="Update Employee"

        android:textSize="20dp"

        android:textStyle="bold" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Name"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <EditText

        android:id="@+id/edtUpdEmplyeeName"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:hint="Enter Employee Name"

        android:padding="10dp" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Salary"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <EditText

        android:id="@+id/edtUpdEmplyeeSalary"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:hint="Enter Employee Salary"

        android:padding="10dp" />

  

    <Button

        android:id="@+id/btnUpdUpdate"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Update" />

 

    <TextView

        android:id="@+id/txtUpdBack"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="right"

        android:text="Back to list"

        android:textSize="12dp"

        android:textStyle="bold" />

  

</LinearLayout>

Step 3. Now open EmployeeUpdate.java and write below code to implement Update operation. Here I have used Bundle and getIntent().getExtras() method to get an id passed from listview. Also used fnSelectRecordById() function of DbHelper.java class to get single record from table by its Id.

EmployeeUpdate.java

package com.example.sqlitedatabaseconnectivity;

  

import android.content.Intent;

import android.database.Cursor;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

  

public class EmployeeUpdate extends AppCompatActivity {

  

    /* Declare object to store controls of activity_main.xml file */

    EditText edtUpdEmplyeeName, edtUpdEmplyeeSalary;

    Button btnUpdUpdate;

    TextView txtUpdBack;

  

    /* Declare object of DbHelper.java */

    DbHelper dbHelper;

  

    /* Final variables */

    private static final String columnEmployeeName = "EmployeeName";

    private static final String columnEmployeeSalary = "EmployeeSalary";

  

    int eId;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_employee_update);

  

        /* Find controls from activity_employee_update.xml file and intialize it to object */

        edtUpdEmplyeeName = (EditText) findViewById(R.id.edtUpdEmplyeeName);

        edtUpdEmplyeeSalary = (EditText) findViewById(R.id.edtUpdEmplyeeSalary);

  

        /* Intialize object of DbHelper.java */

        dbHelper = new DbHelper(this);

  

        Bundle b = getIntent().getExtras();

        if (b != null) {

  

            eId = Integer.valueOf(b.getString("EmployeeId")); /* Get Id from Intent passed from EmployeeList */

  

            Cursor c = dbHelper.fnSelectRecordById(eId); /* Call fnSelectRecordById() of DbHelper.java class to retrieve single record by its Id */

            if (c != null && c.getCount() > 0) {

  

                c.moveToFirst();

  

                String eName = "", eSalary = "";

                eName = c.getString(c.getColumnIndex(columnEmployeeName));

                eSalary = c.getString(c.getColumnIndex(columnEmployeeSalary));

  

                edtUpdEmplyeeName.setText(eName);

                edtUpdEmplyeeSalary.setText(eSalary);

            }

        }

  

        /* Find update button and setting its click event */

        btnUpdUpdate = (Button) findViewById(R.id.btnUpdUpdate);

        btnUpdUpdate.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

  

                /* Getting updated values from edittext */

                String eName = "", eSalary = "";

                eName = edtUpdEmplyeeName.getText().toString();

                eSalary = edtUpdEmplyeeSalary.getText().toString();

  

                /* Call fnUpdate() of DbHelper.java class and passing values through parameters */

                int returnValue = dbHelper.fnUpdate(eId, eName, eSalary);

                if (returnValue != -1) {

                    Toast.makeText(EmployeeUpdate.this, "Employee updated successfully..!!", Toast.LENGTH_SHORT).show();

                    Intent i = new Intent(EmployeeUpdate.this, EmployeeList.class);

                    startActivity(i);

                } else {

                    Toast.makeText(EmployeeUpdate.this, "Try again..!!", Toast.LENGTH_SHORT).show();

                }

            }

        });

  

        /* Finding Back to list textview and setting its click event */

        txtUpdBack = (TextView) findViewById(R.id.txtUpdBack);

        txtUpdBack.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent i = new Intent(EmployeeUpdate.this, EmployeeList.class);

                startActivity(i);

            }

        });

  

    }

}

Delete operation

Step 1. Create new activity with name EmployeeDelete to perform delete operation.

Step 2. Modify its activity_employee_delete.xml file according to requirement. Below is my code for xml file.

activity_employee_delete.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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:gravity="center_horizontal"

    android:orientation="vertical"

    android:padding="15dp"

    tools:context=".EmployeeDelete">

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="15dp"

        android:text="Are you sure you want to delete?"

        android:textSize="20dp"

        android:textStyle="bold" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Name"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <TextView

        android:id="@+id/txtDelEmplyeeName"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="10dp"

        android:text="Name of employee" />

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Salary"

        android:textSize="16dp"

        android:textStyle="bold" />

  

    <TextView

        android:id="@+id/txtDelEmplyeeSalary"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="10dp"

        android:text="Salary of employee" />

  

    <Button

        android:id="@+id/btnDelDelete"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginBottom="5dp"

        android:text="Delete" />

  

    <TextView

        android:id="@+id/txtDelBack"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="right"

        android:text="Back to list"

        android:textSize="12dp"

        android:textStyle="bold" />

  

</LinearLayout>

Step 3. Now open EmployeeDelete.java and write below code to implement Delete operation. Here I have used Bundle and getIntent().getExtras() method to get an id passed from listview. Also used fnSelectRecordById() function of DbHelper.java class to get single record from table by its Id.

EmployeeDelete.java

package com.example.sqlitedatabaseconnectivity;

  

import android.content.Intent;

import android.database.Cursor;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;

  

public class EmployeeDelete extends AppCompatActivity {

  

    /* Declare object to store controls of activity_main.xml file */

    TextView txtDelEmplyeeName, txtDelEmplyeeSalary, txtDelBack;

    Button btnDelDelete;

  

    /* Declare object of DbHelper.java */

    DbHelper dbHelper;

  

    /* Final variables */

    private static final String columnEmployeeName = "EmployeeName";

    private static final String columnEmployeeSalary = "EmployeeSalary";

  

    int eId;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_employee_delete);

  

        /* Find controls from activity_employee_delete.xml file and intialize it to object */

        txtDelEmplyeeName = (TextView) findViewById(R.id.txtDelEmplyeeName);

        txtDelEmplyeeSalary = (TextView) findViewById(R.id.txtDelEmplyeeSalary);

  

        /* Intialize object of DbHelper.java */

        dbHelper = new DbHelper(this);

  

        Bundle b = getIntent().getExtras();

        if (b != null) {

  

            eId = Integer.valueOf(b.getString("EmployeeId")); /* Get Id from Intent passed from EmployeeList */

  

            Cursor c = dbHelper.fnSelectRecordById(eId); /* Call fnSelectRecordById() of DbHelper.java class to retrieve single record by its Id */

            if (c != null && c.getCount() > 0) {

  

                c.moveToFirst();

  

                String eName = "", eSalary = "";

                eName = c.getString(c.getColumnIndex(columnEmployeeName));

                eSalary = c.getString(c.getColumnIndex(columnEmployeeSalary));

  

                txtDelEmplyeeName.setText(eName);

                txtDelEmplyeeSalary.setText(eSalary);

            }

        }

  

        /* Find delete button and setting its click event */

        btnDelDelete = (Button) findViewById(R.id.btnDelDelete);

        btnDelDelete.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

  

                /* Call fnDelete() of DbHelper.java class and pass Id through parameter */

                int returnValue = dbHelper.fnDelete(eId);

                if (returnValue != -1) {

                    Toast.makeText(EmployeeDelete.this, "Employee deleted successfully..!!", Toast.LENGTH_SHORT).show();

                    Intent i = new Intent(EmployeeDelete.this, EmployeeList.class);

                    startActivity(i);

                } else {

                    Toast.makeText(EmployeeDelete.this, "Try again..!!", Toast.LENGTH_SHORT).show();

                }

            }

        });

  

        /* Finding Back to list textview and setting its click event */

        txtDelBack = (TextView) findViewById(R.id.txtDelBack);

        txtDelBack.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent i = new Intent(EmployeeDelete.this, EmployeeList.class);

                startActivity(i);

            }

        });

  

    }

}

Your Project Structure may look like,

Now run this application in AVD or in your mobile. The output screen shown below.

Insert and Select operation

Update operation

Delete operation

I hope you like this blog. If you have any query, please comment below. Thank You… :)