Hey, friends here is an Android SQLite Database Example. You may already know that we have SQLite database in android that we can use as a local SQL Database for our android application.
This Android SQLite Database Example will cover Creating Database, Creating Tables, Creating Records, Reading Records, Updating Records and Deleting Records in Android SQLite Database. After going through this post you will be having a complete idea about using SQLite database for your Android Application. So let’s start.
Table of Contents
What is SQLite?
SQLite is an SQL Database. I am assuming here that you are familiar with SQL databases. So in SQL database, we store data in tables. The tables are the structure of storing data consisting of rows and columns. We are not going in depth of what is an SQL database and how to work in SQL database. If you are going through this post, then you must know the Basics of SQL.
What is CRUD?
As the heading tells you here, we are going to learn the CRUD operation in SQLite Database.
But what is CRUD? CRUD is nothing but an abbreviation for the basic operations that we perform in any database. And the operations are
- Create
- Read
- Update
- DeleteÂ
Android SQLite Database Example App Apk
- Before moving ahead on this tutorial if you want to know what we will be building, you can get the final apk of this tutorial from the link given below.
Android SQLite Database Example App Apk Download
Android SQLite Database Example
Creating a new Android Studio Project
- As always we will create a new Android Studio Project. For this example, I have a new project named SQLiteCRUDExample.
- Once your project is loaded, we can start working on it.
The Database Structure
- The first thing needed is the database structure. We create database structure according to the system. But here we are not building an application, and it is only an example demonstrating the use of SQLite Database. So for this, I will use the following table structure.
- Now we have only a single table, but in real-world scenarios, you will have multiple tables with some complex relationships. Also, remember one thing whenever you create a table create a column named id with int as PRIMARY KEY and AUTOINCREMENT. (If you are confused don’t worry we will see now how do we create tables in database using SQL).
SQL Queries
- Now let’s see how we can create the above table in our SQLite database.
Creating the Table
1 2 3 4 5 6 7 8 9 |
CREATE TABLE employees ( id INTEGER NOT NULL CONSTRAINT employees_pk PRIMARY KEY AUTOINCREMENT, name varchar(200) NOT NULL, department varchar(200) NOT NULL, joiningdate datetime NOT NULL, salary double NOT NULL ); |
Creating a new Record
1 2 3 4 5 6 |
INSERT INTO employees (name, department, joiningdate, salary) VALUES ('Belal Khan', 'Technical', '2017-09-30 10:00:00', '40000'); |
Reading All Existing Records
1 2 3 |
SELECT * FROM employees; |
Reading Specific Record
1 2 3 |
SELECT * FROM employees WHERE id = 1; |
Note:Â * means selecting all the columns, if you want a specific column or multiple columns but not all you can write names of the columns like SELECT name, department.
Updating a Record
1 2 3 4 5 6 7 8 |
UPDATE employees SET name = 'Belal Haque', department = 'Research and Development', salary = '100000' WHERE id = 1; |
Deleting a Record
1 2 3 |
DELETE FROM employees WHERE id = 1; |
These are just some simple basics operations, but we can perform many tasks in our database. For this, you need to learn SQL in detail.
Note: SQL Queries are not case sensitive.Â
User Interface Design
- To implement all the above-given queries in our application, we need an Interface from where we can accomplish these tasks. Now, lets think about the screens that we need to make an app that will perform all the above-given queries with user interaction.
Adding a new Employee
- The first thing is adding a new record to our database, and for this, we can use the following screen.
- As you can see we have EditText, Button, Spinner and some TextViews. To create the above interface, you can use the following XML code. You need to paste the following code inside activity_main.xml which is generated by default in any project because this will be the first screen for our application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedlearning.sqlitecrudexample.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" android:padding="16dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="12dp" android:text="Add a new Employee" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Employee Name" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:paddingLeft="6dp" android:text="Select Department" /> <Spinner android:id="@+id/spinnerDepartment" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/departments" /> <EditText android:id="@+id/editTextSalary" android:layout_width="match_parent" android:layout_height="wrap_content" android:digits="0123456789" android:hint="Enter Employee Salary" android:inputType="number" /> <Button android:id="@+id/buttonAddEmployee" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Add Employee" /> <TextView android:id="@+id/textViewViewEmployees" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:text="View Employees" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> |
- For the spinner that we used in the above screen, we need to define an Array as the entries for the spinner. So go inside values->strings.xml and modify it as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<resources> <string name="app_name">SQLiteCRUDExample</string> <array name="departments"> <item>Technical</item> <item>Support</item> <item>Research and Development</item> <item>Marketing</item> <item>Human Resource</item> </array> </resources> |
Fetching All the Employees
- Now after storing employee to the database, we also need to see all the stored employee from the database. For this, we can use a ListView.
- So, to create a new EmptyActivity in your project named EmployeeActivity. It will create a java file named EmployeeActivity.java and a layout file called activity_employee.xml.
- For this screen we can use the following design.
- This screen contains a only a ListView. The xml for the above screen is below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedlearning.sqlitecrudexample.EmployeeActivity"> <ListView android:id="@+id/listViewEmployees" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> |
- But here we will not use a simple ListView as we need to display multiple items in the List we will be using a Custom ListView. You can learn about creating custom ListView from this tutorial -> Creating a CustomListview.
- And for the ListView item we need one more layout as well, so create one more layout file named list_layout_employee.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<?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" android:padding="8dp"> <LinearLayout android:layout_width="230dp" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/textViewName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_marginTop="10dp" android:text="Belal Khan" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewDepartment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Technical" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" /> <TextView android:id="@+id/textViewSalary" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="INR 40000" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" /> <TextView android:id="@+id/textViewJoiningDate" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="2017-09-30 10:00:00" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <Button android:id="@+id/buttonEditEmployee" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="@color/colorPrimary" android:text="Edit" /> <Button android:id="@+id/buttonDeleteEmployee" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="@color/colorAccent" android:text="Delete" /> </LinearLayout> </LinearLayout> |
- The above xml code will generate the following layout.
Updating the Employee
- Now we will create one more layout file (not a new activity only a layout file because we will edit the employee in an alert dialog)Â to update the employee data. So create a new layout file named dialog_update_employee.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?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:padding="16dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="12dp" android:text="Edit Employee" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Employee Name" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:paddingLeft="6dp" android:text="Select Department" /> <Spinner android:id="@+id/spinnerDepartment" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/departments" /> <EditText android:id="@+id/editTextSalary" android:layout_width="match_parent" android:layout_height="wrap_content" android:digits="0123456789" android:hint="Enter Employee Salary" android:inputType="number" /> <Button android:id="@+id/buttonUpdateEmployee" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Update" /> </LinearLayout> |
- This code will generate the following design.
- We don’t need a separate design for deleting the employee as we will be doing it from the button that we created on the List.
- So we are done with the interface design. Now lets start coding.
Coding the Application
Adding an Employee
- We will perform this operation inside MainActivity.java so inside this file write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
package net.simplifiedlearning.sqlitecrudexample; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final String DATABASE_NAME = "myemployeedatabase"; TextView textViewViewEmployees; EditText editTextName, editTextSalary; Spinner spinnerDepartment; SQLiteDatabase mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewViewEmployees = (TextView) findViewById(R.id.textViewViewEmployees); editTextName = (EditText) findViewById(R.id.editTextName); editTextSalary = (EditText) findViewById(R.id.editTextSalary); spinnerDepartment = (Spinner) findViewById(R.id.spinnerDepartment); findViewById(R.id.buttonAddEmployee).setOnClickListener(this); textViewViewEmployees.setOnClickListener(this); //creating a database mDatabase = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null); } //this method will validate the name and salary //dept does not need validation as it is a spinner and it cannot be empty private boolean inputsAreCorrect(String name, String salary) { if (name.isEmpty()) { editTextName.setError("Please enter a name"); editTextName.requestFocus(); return false; } if (salary.isEmpty() || Integer.parseInt(salary) <= 0) { editTextSalary.setError("Please enter salary"); editTextSalary.requestFocus(); return false; } return true; } //In this method we will do the create operation private void addEmployee() { } @Override public void onClick(View view) { switch (view.getId()) { case R.id.buttonAddEmployee: addEmployee(); break; case R.id.textViewViewEmployees: startActivity(new Intent(this, EmployeeActivity.class)); break; } } } |
- In the above code you see we used a method openOrCreateDatabase().
- This method takes 3 parameters.
First parameter is the database name as String, that we need to open. Lets assume we passed some name “xyz” as the first parameter then if there exist a database named “xyz” it will open it, if no database found with the specified name it will create a new database named “xyz” and will open it.
Second Parameter is the open mode as int. We have some predefined values for it, right now we are using MODE_PRIVATE and it simply means that only this application can access this database. - Now we will create a method to create the Employee table. So create a method named createEmployeeTable().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//this method will create the table //as we are going to call this method everytime we will launch the application //I have added IF NOT EXISTS to the SQL //so it will only create the table when the table is not already created private void createEmployeeTable() { mDatabase.execSQL( "CREATE TABLE IF NOT EXISTS employees (\n" + " id int NOT NULL CONSTRAINT employees_pk PRIMARY KEY,\n" + " name varchar(200) NOT NULL,\n" + " department varchar(200) NOT NULL,\n" + " joiningdate datetime NOT NULL,\n" + " salary double NOT NULL\n" + ");" ); } |
- Now just call this method just after calling the openOrCreateDatabase() method. In the above method we are just calling the method execSQL() to create our database table. The execSQL() method takes String as a parameter and the String is actually the SQL query that we need to execute.
- Remember we use execSQL() method only for creating table, inserting or updating records. We cannot use it to retrieve values.
- Till now we have the database, the table now we need to insert the employee in the table and we need to do this inside addEmployee() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
private void addEmployee() { String name = editTextName.getText().toString().trim(); String salary = editTextSalary.getText().toString().trim(); String dept = spinnerDepartment.getSelectedItem().toString(); //getting the current time for joining date Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); String joiningDate = sdf.format(cal.getTime()); //validating the inptus if (inputsAreCorrect(name, salary)) { String insertSQL = "INSERT INTO employees \n" + "(name, department, joiningdate, salary)\n" + "VALUES \n" + "(?, ?, ?, ?);"; //using the same method execsql for inserting values //this time it has two parameters //first is the sql string and second is the parameters that is to be binded with the query mDatabase.execSQL(insertSQL, new String[]{name, dept, joiningDate, salary}); Toast.makeText(this, "Employee Added Successfully", Toast.LENGTH_SHORT).show(); } } |
- Now you can test your application for the Create Operation.
- Now lets move towards fetching the stored employees which we call the Read Operation.
Retrieving All Employees
- We will do this operation inside EmployeeActivity.java. But before fetching the employees, we need two more java classes to display employees in the list. The first class is a regular java class to store the employee as an object and a CustomAdapter class for the ListView.
Employee Model
- Create a simple java class named Employee.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package net.simplifiedlearning.sqlitecrudexample; /** * Created by Belal on 9/30/2017. */ public class Employee { int id; String name, dept, joiningDate; double salary; public Employee(int id, String name, String dept, String joiningDate, double salary) { this.id = id; this.name = name; this.dept = dept; this.joiningDate = joiningDate; this.salary = salary; } public int getId() { return id; } public String getName() { return name; } public String getDept() { return dept; } public String getJoiningDate() { return joiningDate; } public double getSalary() { return salary; } } |
- Now we will create a custom adapter class for our ListView.
Custom ListView Adapter
- Create a java class named EmployeeAdapter and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
package net.simplifiedlearning.sqlitecrudexample; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.List; /** * Created by Belal on 9/30/2017. */ public class EmployeeAdapter extends ArrayAdapter<Employee> { Context mCtx; int listLayoutRes; List<Employee> employeeList; SQLiteDatabase mDatabase; public EmployeeAdapter(Context mCtx, int listLayoutRes, List<Employee> employeeList, SQLiteDatabase mDatabase) { super(mCtx, listLayoutRes, employeeList); this.mCtx = mCtx; this.listLayoutRes = listLayoutRes; this.employeeList = employeeList; this.mDatabase = mDatabase; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(mCtx); View view = inflater.inflate(listLayoutRes, null); //getting employee of the specified position Employee employee = employeeList.get(position); //getting views TextView textViewName = view.findViewById(R.id.textViewName); TextView textViewDept = view.findViewById(R.id.textViewDepartment); TextView textViewSalary = view.findViewById(R.id.textViewSalary); TextView textViewJoiningDate = view.findViewById(R.id.textViewJoiningDate); //adding data to views textViewName.setText(employee.getName()); textViewDept.setText(employee.getDept()); textViewSalary.setText(String.valueOf(employee.getSalary())); textViewJoiningDate.setText(employee.getJoiningDate()); //we will use these buttons later for update and delete operation Button buttonDelete = view.findViewById(R.id.buttonDeleteEmployee); Button buttonEdit = view.findViewById(R.id.buttonEditEmployee); return view; } } |
- Now we can fetch the employees to display them in the ListView.
Retrieving and Displaying in ListView
- Come inside EmployeeActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
package net.simplifiedlearning.sqlitecrudexample; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class EmployeeActivity extends AppCompatActivity { List<Employee> employeeList; SQLiteDatabase mDatabase; ListView listViewEmployees; EmployeeAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_employee); listViewEmployees = (ListView) findViewById(R.id.listViewEmployees); employeeList = new ArrayList<>(); //opening the database mDatabase = openOrCreateDatabase(MainActivity.DATABASE_NAME, MODE_PRIVATE, null); //this method will display the employees in the list showEmployeesFromDatabase(); } private void showEmployeesFromDatabase() { //we used rawQuery(sql, selectionargs) for fetching all the employees Cursor cursorEmployees = mDatabase.rawQuery("SELECT * FROM employees", null); //if the cursor has some data if (cursorEmployees.moveToFirst()) { //looping through all the records do { //pushing each record in the employee list employeeList.add(new Employee( cursorEmployees.getInt(0), cursorEmployees.getString(1), cursorEmployees.getString(2), cursorEmployees.getString(3), cursorEmployees.getDouble(4) )); } while (cursorEmployees.moveToNext()); } //closing the cursor cursorEmployees.close(); //creating the adapter object adapter = new EmployeeAdapter(this, R.layout.list_layout_employee, employeeList); //adding the adapter to listview listViewEmployees.setAdapter(adapter); } } |
- Now try running the application to see the Read Operation.
Updating an Employee
- We have done with Create and Read, now lets do the Update Operation. We will perform it inside the EmployeeAdapter class.
- For the Update operation we need two new methods inside the EmployeeAdapter.java. One is to update the employee and the second one is to reload the employee from database to show updated information.
- So inside the class you need to make below given two methods named updateEmployee() and reloadEmployeesFromDatabase() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
private void updateEmployee(final Employee employee) { final AlertDialog.Builder builder = new AlertDialog.Builder(mCtx); LayoutInflater inflater = LayoutInflater.from(mCtx); View view = inflater.inflate(R.layout.dialog_update_employee, null); builder.setView(view); final EditText editTextName = view.findViewById(R.id.editTextName); final EditText editTextSalary = view.findViewById(R.id.editTextSalary); final Spinner spinnerDepartment = view.findViewById(R.id.spinnerDepartment); editTextName.setText(employee.getName()); editTextSalary.setText(String.valueOf(employee.getSalary())); final AlertDialog dialog = builder.create(); dialog.show(); view.findViewById(R.id.buttonUpdateEmployee).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = editTextName.getText().toString().trim(); String salary = editTextSalary.getText().toString().trim(); String dept = spinnerDepartment.getSelectedItem().toString(); if (name.isEmpty()) { editTextName.setError("Name can't be blank"); editTextName.requestFocus(); return; } if (salary.isEmpty()) { editTextSalary.setError("Salary can't be blank"); editTextSalary.requestFocus(); return; } String sql = "UPDATE employees \n" + "SET name = ?, \n" + "department = ?, \n" + "salary = ? \n" + "WHERE id = ?;\n"; mDatabase.execSQL(sql, new String[]{name, dept, salary, String.valueOf(employee.getId())}); Toast.makeText(mCtx, "Employee Updated", Toast.LENGTH_SHORT).show(); reloadEmployeesFromDatabase(); dialog.dismiss(); } }); } private void reloadEmployeesFromDatabase() { Cursor cursorEmployees = mDatabase.rawQuery("SELECT * FROM employees", null); if (cursorEmployees.moveToFirst()) { employeeList.clear(); do { employeeList.add(new Employee( cursorEmployees.getInt(0), cursorEmployees.getString(1), cursorEmployees.getString(2), cursorEmployees.getString(3), cursorEmployees.getDouble(4) )); } while (cursorEmployees.moveToNext()); } cursorEmployees.close(); notifyDataSetChanged(); } |
- The update operation is same as the insert operation, we changed the query only to update from insert. If you are having any confusion understanding the codes please comment and I will help you.
- Now we need to modify the getView() method of EmployeeAdapter as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(mCtx); View view = inflater.inflate(listLayoutRes, null); final Employee employee = employeeList.get(position); TextView textViewName = view.findViewById(R.id.textViewName); TextView textViewDept = view.findViewById(R.id.textViewDepartment); TextView textViewSalary = view.findViewById(R.id.textViewSalary); TextView textViewJoiningDate = view.findViewById(R.id.textViewJoiningDate); textViewName.setText(employee.getName()); textViewDept.setText(employee.getDept()); textViewSalary.setText(String.valueOf(employee.getSalary())); textViewJoiningDate.setText(employee.getJoiningDate()); Button buttonDelete = view.findViewById(R.id.buttonDeleteEmployee); Button buttonEdit = view.findViewById(R.id.buttonEditEmployee); //adding a clicklistener to button buttonEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { updateEmployee(employee); } }); return view; } |
- Now you can test the Update Operation.
Deleting an Employee
- We have done with Create, Read and Update. Now the last operation is the Delete Operation. So lets do this to complete the CRUD for this tutorial.
- We will do the deletion also in the EmployeeAdapter class. The operation is same we just need to change the SQL String to perform delete operation the rest part is exactly the same.
- So to make the delete operation again modify the getView() of EmployeeAdapter as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
@NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(mCtx); View view = inflater.inflate(listLayoutRes, null); final Employee employee = employeeList.get(position); TextView textViewName = view.findViewById(R.id.textViewName); TextView textViewDept = view.findViewById(R.id.textViewDepartment); TextView textViewSalary = view.findViewById(R.id.textViewSalary); TextView textViewJoiningDate = view.findViewById(R.id.textViewJoiningDate); textViewName.setText(employee.getName()); textViewDept.setText(employee.getDept()); textViewSalary.setText(String.valueOf(employee.getSalary())); textViewJoiningDate.setText(employee.getJoiningDate()); Button buttonDelete = view.findViewById(R.id.buttonDeleteEmployee); Button buttonEdit = view.findViewById(R.id.buttonEditEmployee); //adding a clicklistener to button buttonEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { updateEmployee(employee); } }); //the delete operation buttonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(mCtx); builder.setTitle("Are you sure?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String sql = "DELETE FROM employees WHERE id = ?"; mDatabase.execSQL(sql, new Integer[]{employee.getId()}); reloadEmployeesFromDatabase(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog dialog = builder.create(); dialog.show(); } }); return view; } |
- So the operation is complete and now you can test all the operation in your application and you should see something like this.
Android SQLite Database Example Source Code
- If you are facing any troubles building, the application then don’t worry here is my source code for you.
Android SQLite Database Example Source Code Download
So that’s all for this Android SQLite Database Example friends. I hope you liked it. For any confusions or questions just leave your comments below. Please write your real name in the comment box as I don’t approve comments with spam names.
You can share this post to help us. Thank You 🙂