Android Room

SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

Room is a persistence library, part of the Android Jetpack. We can easily work with SQLite with room. First of all make sure you add room library into build.gradle.

implementation 'androidx.room:room-runtime:2.2.5'
annotationProcessor 'androidx.room:room-compiler:2.2.5'


Now let's try to understand working of Room with an example, for employee list. First of all create entity class Employee as below:

package com.theitbulls.shareprefex.beans;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity(tableName = "employee")
public class Employee {
    public static final String NAME = "name";
    public static final String AGE = "age";
    public static final String SALARY = "salary";

    @PrimaryKey(autoGenerate = true)
    public long id;

    @ColumnInfo(name = NAME)
    public String empName;

    @ColumnInfo(name = SALARY)
    public double salary;

    @ColumnInfo(name = AGE)
    public int age;
}


In above Emplyee class annotation @Entity will use to create table as we provide tableName, and we also use anotation @ColumnInfo will use to create columns of table's. So let's us create Dao as below


package com.theitbulls.shareprefex.dao;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import com.theitbulls.shareprefex.beans.Employee;

import java.util.List;

@Dao
public interface EmployeeDAO {
    @Insert
    void addEmp(Employee employee);

    @Delete
    void deleteEmp(Employee employee);

    // here ':id' will replace with function arguments value i.e long id
    @Query("DELETE FROM Employee where Employee.id = :id")
    void deleteEmp(long id);

    @Update
    void updateEmp(Employee employee);

    @Query("SELECT * FROM Employee")
    List<Employee> list();
}

In above EmplyeeDao, we use many annotation like @Dao, @Insert, @Update, @Delete and @Query.


Now last create abstract EmployeeDatabase class having abstract method i.e. empDao().

package com.theitbulls.shareprefex.db;

import androidx.room.Database;
import androidx.room.RoomDatabase;

import com.theitbulls.shareprefex.beans.Employee;
import com.theitbulls.shareprefex.dao.EmployeeDAO;

@Database(entities = {Employee.class}, version = 1, exportSchema = false)
public abstract class EmployeeDatabase extends RoomDatabase {
    public static final String DB_NAME = "emp_db";

    public abstract EmployeeDAO empDao();
}


Note: Please keep in mind any SQLite operation like add, delete, update etc... can not perform in main thread, so we use AsyncTask to perform all such operations. as below:

public class AddEmployeeTask extends AsyncTask<Void, Void, Boolean> {
    private Context mContext;
    private Employee employee;

    public AddEmployeeTask(Context mContext, Employee employee) {
        this.mContext = mContext;
        this.employee = employee;
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        try {
            EmployeeDatabase db = Room.databaseBuilder(mContext, EmployeeDatabase.class, EmployeeDatabase.DB_NAME).build();
            db.empDao().addEmp(employee);

            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean added) {
        if (added) {
            Toast.makeText(mContext, "Employee data added successfully.", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(mContext, "Employee data could not added.", Toast.LENGTH_SHORT).show();
    }
}

Create your delete, update, list task accordingly. Now we will show you how to add Employee record:

Employee emp = new Employee();
emp.empName = "John Carlo";
emp.age = 24;
emp.salary = 80000;

new AddEmployeeTask(this, emp).execute();