Sunday , November 28 2021

Android SQLite Database Example – CRUD Operation in SQLite – Android Coding by DMTechnolab

Hey guys here is an Android SQLite Database example. You may already know that we have a SQLite database in Android which we can use as a local SQL database for our Android application.

Creating this Android SQLite database instance will cover the database, Creating tables, creating records, reading records, updating records, and deleting records SQLite Database in Android. After going through this post you will get to know fully about using SQLite database for your Android application. Let’s start.

What is SQLite?

SQLite is a SQL database. I am assuming here that you are familiar with SQL database. So in SQL database, we store data in tables. A data storing structure consisting of tables and rows and columns. We are not going into the depth of what a SQL database is and how it works in a SQL database. If you are going through this post, then you should know Basics of sql.

What is CRUD?

As the title tells you here, we are going to learn the CRUD operation in the SQLite database.
But what is CRUD? CRUD There is nothing but an abbreviation for basic functions that we do in any database. And operation are

  • CWrit
  • Read
  • UPdate
  • Dego

Android SQLite Database Example App Apk

  • Before proceeding on this tutorial, if you want to know what we are building, you can get the last apk of this tutorial from the link given below.

Android SQLite Database Example App Apk Download

Android SQLite Database Example

Create 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.

Database structure

  • Database structure is needed first. We create database structure according to the system. But here we are not building an application, and this is just an example that demonstrates the use of SQLite database. So for this, I will use the following table structure.
Android SQLite Database Example
Database structure
  • Now we have only one table, but in real-world scenarios, you will have many tables with some complex relationships. Also, remember one thing, whenever you create a table, you create a column named int Primary Key and Automation. (If you are confused then do not worry that we will now see how we create tables in the database using SQL).

SQL queries

  • Now let us see how we can create the above table in our SQLite database.
make the table

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
);

Create a new record

INSERT INTO employees 
(name, department, joiningdate, salary)
VALUES 
('Belal Khan', 'Technical', '2017-09-30 10:00:00', '40000');

Read all current records

SELECT * FROM employees;

Reading specific records

SELECT * FROM employees WHERE id = 1;

pay attention: * Selecting all columns means if you want a specific column or multiple columns, but cannot write the names of all columns Selected Name, Department.

Updating a record

UPDATE employees 
SET 
name="Belal Haque", 
department="Research and Development", 
salary = '100000' 
WHERE id = 1;

Delete a record

DELETE FROM employees WHERE id = 1;

These are some simple basics, but we can do many tasks in our database. For this you have to learn SQL in detail.

Note: SQL queries are not sensitive.

User interface design

  • To implement all the above queries in our application, we need an interface from where we can complete these tasks. Now, lets think about the screens that we need to build an app that will interact with the user with all the above queries.

Add a new employee

  • The first thing is adding a new record to our database, and for this we can use the following screen.
Record making
Record making
  • 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 will have to paste the following code inside activity_main.xml which is generated by default in any project as this will be the first screen of our application.
<?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 entries for the spinner. So go in Value-> wire. xml And modify it as below.
<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>

Bring all employees

  • Now after storing the employee in the database, we also have to see all the stored employee from the database. For this we can use a ListView.
  • So, to create a new EmptyActivity in the project named Employeeism. This will create a java file named Employeeism Java And is called a layout file activity_employee.xml
Create an empty activity
Create free activity
  • For this screen we can use the following design.

View employee screen

  • This screen contains only one list View. The xml for the above screen is below.
<?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 list view because we need to display many items in the list which we will use a custom list view. You can learn how to create a custom list view from this tutorial -> Creating a CustomListview.
  • And we also need another layout for the ListView item, so create another layout file named list_layout_employee.xml And write the following xml code.
<?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.

Employee list

Employee update

  • Now we will create another layout file (The new activity is not just a layout file because we will edit the employee in an alert dialog) To update employee data. So create a new layout file by name Dial_update_employee.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: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.

Update employee

  • We do not need a different design to remove the employee because we will do it with the button that we created in the list.
  • So we are done with interface design. Now let’s start coding.

Application coding

Add an employee

  • We will do this operation in MainActivity.java So write the following code inside this file.
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 that we have used a method OpenOrCreateDatabase ().
  • Adopts this method 3 parameters.
    First parameter Database name is String, That we need to open. Let’s assume that we named something “Zies” As the first parameter if there exists a database name “Zies” This will open it, if no database is found with the specified name then it will create a new database named “Zies” And will open it.
    Second parameter As is open mode int. We have some predefined values ​​for it, now we are using it MODE_PRIVATE And it simply means that only this application can access this database.
  • Now we will create a method to create Staff table. So create a method named createEmployeeTable ().
//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 NULLn" +
                        ");"
        );
    }

  • Now call this method after just calling OpenOrCreateDatabase () way. In the above method we are just saying the method FSQL () To create our database table. The executor () method takes the string as a parameter and the string is actually the SQL query we need to execute.
  • Remember we use Executor () Only method for creating, inserting or updating records. We cannot use it to retrieve values.
  • So far we have the database, the table now we need to insert the employee into the table and we need to do it in addEmployee () way.
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 Create operation.
Android sqlite database instance - create operation
Android SQLite Database Example – Create Operation
  • Now let’s move towards bringing the stored employees we call Read operation.

Retrieving all employees

  • We will do this operation in Employeeism.java. But before bringing the staff, we need two more Java classes to display the staff in the list. The first class is a regular Java class for storing as an employee and an object CustomAdapter Class for list View.
Employee model
  • Create a simple java class by name Staff.java And write the following code.
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 list view optimizer
  • Create a Java class by name Employee adapter And write the following code.
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 bring employees to display in the list.
Retrieve and display in list view
  • come inside Employeeism.java And write the following code.
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 Read operation.
Android sqlite database example - read operation
Android SQLite Database Example – Read Operation

Updating an employee

  • We have been together Create and Read, Now, let us perform the update operation. We will demonstrate this inside the EmployeeAdapter class.
  • We need two new methods for update operation EmployeeAdapter.java. One is to update the employee and the other is to reload the employee from the database to show the updated information.
  • So inside the class you have to name two methods given below Update staff () And reloadEmployeesFromDatabase () way.
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 similar to the insert operation, we have changed the query to update only from insert. If you are having any problem in understanding the code, then please comment and I will help you.
  • Now we need to modify it getView () EmployeeAdapter’s method as below.
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.
Android cyclite database example - update operation
Android SQLite Database Example – Update Operation

Remove an employee

  • We have been together CWrit, Read and UPdate. Now the last operation is Dego operation. So do this to complete CRUD for this tutorial.
  • We will also delete Employee adapter class. The operation is what we need to change the SQL string to remove, the rest of it is exactly the same.
  • So to modify the delete operation again getView () Of EmployeeAdapter as below.
@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 operations in your application and you should see something like this.
Android SQLite Database Example
Android SQLite Database Example

Android SQLite Database Example Source Code

  • If you are facing any problem building, don’t worry here the application is my source code for you.

Download android sqlite database example source code

So this is all for this Android SQLite database example friends. I hope you like it. Just leave your comments below for any confusion or questions. Please enter your real name in the comment box as I do not accept comments with spam names.

You can share this post to help us. Thank you 4


Source link

About dmtechnolab

Check Also

Simplified Coding

Android Espresso Tutorial – Testing Fragment in Isolation – Android Coding by DMTechnolab

Welcome to another tutorial in the Android test series. And this post is called Android …

Leave a Reply

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