Android Development

Room Database in android java

Room Database in android java

Hi everyone, in this post, we will discuss Room Database in android java.

Below are all steps covered in this blog

  • How to use the Room database
  • How to add Room Database in android studio
  • Insert,Update,Delete record
  • How to pass query in Database

What is a Room?

  • The Room strong library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.
  • Normally Room databases are fast created and have good performance like reading, updating and deleting records. Room Database makes everything easy and fast
  • Room Database more detail open this link: https://developer.android.com/training/data-storage/room/

Components of Room Here room have main 3 components

Entity:

  • Instead of creating the SQLite table, we will create the Entity. An entity is nothing but a model class annotated with @Entity. The variables of this class are our columns, and the class is our table.

Database:

  • It is an abstract class where we define all our entities.

DAO:

  • Stands for Data Access Objects. It is an interface that defines all the operations that we need to perform in our database.

Demo App Create

  • First, we create a new project in android studio.
  • Name of my project “Room DataBase”

Adding Dependencies

  • Add needed dependencies for the room database.
  • Android studio in this file add dependencies “build.gradle”.
  • See the below image and add the latest version room database replace here “$room_version” add original version

First, we will create DAO class:

  • This DAO class-main work intermediary between the user and database. All performed operations are defined here.
  • Below create StudentDao class
				
					@Dao
public interface StudentDao {

@Query("SELECT * FROM Student")
List<Student> getAll();

@Insert
void insert(Student student);

@Update
void updateTask(Student student);

@Delete
void deleteTask(Student student);
}
				
			

Nowhere explain all components of StudentDao Class

  • Compulsory add class upper “@Dao” keyword
  • Three methods create insert, update, delete
  • Most important thing here is “@Query”

What is a Query?

  • Using query to get database existing record.
  • @Query(“SELECT * FROM Student”) this query gets all student records.
  • But the user wants to get only the standard “5” student record and only get how to pass a query?
				
					  @Query("SELECT * FROM STUDENT where std = :std")

    List<Student> dataCheck(String std);
				
			
  • Here “std” id table field name
  • Call this method “data check(String std)” pass a string in “5” and database in getting only 5 stander student record
  • So this concept use the query parameter

Second steps create student model class

				
					@Entity(tableName = "student")
public class Student implements Serializable {

@PrimaryKey(autoGenerate  = true)
private int id;

@ColumnInfo(name = "std")
private int std;

@ColumnInfo(name = "name")
private String name;

public int getId() {
    return id;
  }

public void setId(int id) {
    this.id = id;
  }

public int getStd() {
    return std;
  }

public void setStd(int std) {
    this.std = std;
  }

public String getName() {
    return name;
  }

public void setName(String name) {
    this.name = name;
  }
}
				
			
  • PrimaryKey: auto increment values
  • tableName : user wants to set the table name
  • ColumnInfo: give the table in columns name

Third steps Create Database class:

				
					@Database(entities = {Student.class}, version = 1)
public abstract class AppDatabase extends     RoomDatabase {
public abstract Student studentDao();
}
				
			
  • User wants to add multiple tables how can add like that:

@Database(entities = {Student.class,Abc.class,Xyz.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract Student studentDao(); }

  • To create a new model class like Abc.class and Xyz.class etc same method.

Fourth step inserts, update and delete records create separate method:

				
					public class InsertUpdateDeletRecord {

    private String DB_NAME = "db_task";

    private Student Student;
    public studentRepository(Context context) {
        Student = Room.databaseBuilder(context, Student.class, DB_NAME).build();
    }

    public void insertTask(String std,String name) {

        insertTask(std, name);
    }

    public void insertTask(String std,String name) {
        Student student = new Student();
        student.setstd(std);
        student.setname(name);

        insertTask(student);
    }

    public void insertTask(final Student student) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().insertTask(student);
                return null;
            }
        }.execute();
    }

    public void updateTask(final Student student) {
        student.setModifiedAt(AppUtils.getCurrentDateTime());

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().updateTask(student);
                return null;
            }
        }.execute();
    }

    public void deleteTask(final int id) {
        final LiveData<student> task = getTask(id);
        if(task != null) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    Student.daoAccess().deleteTask(task.getValue());
                    return null;
                }
            }.execute();
        }
    }

    public void deleteTask(final student student) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().deleteTask(student);
                return null;
            }
        }.execute();
    }

 }
				
			

Sample Implementation of basic CRUD operations using ROOM

Insert:

				
					 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext( ));
 String std = "5";
 String name = Android";
 insertUpdateDeletRecord.insertTask(title, 
 description);
				
			

Update:

				
					 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext( ));
 Student student = 
 insertUpdateDeletRecord.getTask(2);
 student.setName("Java");
 student.setStd("6");
 insertUpdateDeletRecord.updateTask(student);
				
			

Update:

				
					 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext());
 insertUpdateDeletRecord.deleteTask(3);
				
			
Share On: