Android MVVM Room LiveData Full CRUD App → RoomDatabase and DAO interface – Camposha

Android MVVM Room LiveData Full CRUD App

Android Room LiveData CRUD

RoomDatabase and DAO interface

RoomDatabase and DAO Interface

In this lesson we will create our RoomDatabase as well as our DAO interface.This lesson is part of Android MVVM LiveData Room CRUD course.

(a). ScientistsDAO.java

DAO stands for Data Access Object. Thus the object of this interface will allow us access our data via methods we are going to define. This is an interface hence the methods will be abstract.

However they will be decorated with special annotations which Room will use to infer our intentions.

For example:

    @Insert
    long  insert(Scientist scientist);

tells Room we want to insert a scientist object. Room understands that annotation. It also understands the Scientist object because it was defined as our entity.

Thus with Room we have the advantage of not having to write raw SQL statements.

 

Video Lesson

Step 1: Add imports

Create an interface known as ScientistsDAO and add the following import statements:

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

import java.util.List;

Step 2. Define our DAO interface

Then define an interface annotated with @Dao to mark it as our Data Access Object:

@Dao
public interface ScientistDAO {

Step 3: Insert

Methods annotated with @Insert can return either void, long, Long, long[],Long[] or List.


    @Insert
    long  insert(Scientist scientist);

The above method will allow us insert a Scientist object to our SQLite database.

Step 4: Update

Update methods must either return void or return int (the number of updated rows).

    @Update
    int update(Scientist scientist);

The int returned above is the number of rows updated after calling the above method.

Step 5: Delete

Deletion methods must either return void or return int (the number of deleted rows).

    @Delete
    int  delete(Scientist scientist);

The method above allows us delete a scientist object via Rooom.

To delete all rows from SQLite via Room:

    @Query("delete from ScientistTB")
    int deleteAll();

Step 6: Select

Below is our method for selecting data:

    @Query("select * from ScientistTB")
    LiveData<List<Scientist>> selectAll();

We have supplied a ‘@Query’ annotated with our SQL statement for selecting all data from ScientistsTB.
You can see we are returning LiveData object with a generic list of scientists as the generic parameter.
Observers will then be able to observe that LiveData for changes.

FULL CODE

Here is the full code for the ScientistsDAO.java:

package info.camposha.roomlivedatacrudapp.data.dao;

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

import java.util.List;
import info.camposha.roomlivedatacrudapp.data.model.Scientist;

@Dao
public interface ScientistDAO {
    //NB= Methods annotated with @Insert can return either void, long, Long, long[],
    // Long[] or List<Long>.
    @Insert
    long  insert(Scientist scientist);
    //Update methods must either return void or return int (the number of updated rows).
    @Update
    int update(Scientist scientist);
    //Deletion methods must either return void or return int (the number of deleted rows).
    @Delete
    int  delete(Scientist scientist);
    @Query("select * from ScientistTB")
    LiveData<List<Scientist>> selectAll();
    //NB= Deletion methods must either return void or return int (the number of deleted
    // rows).
    @Query("delete from ScientistTB")
    int deleteAll();
}
//end

(b). MyRoomDB.java

This abstract class will:

  1. Represent our Room Database.
  2. It will also define our database entities or tables.
  3. It will also define our database version.

Step 1. Add Imports

Start by adding imports:

import android.content.Context;

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

import info.camposha.roomlivedatacrudapp.data.dao.ScientistDAO;
import info.camposha.roomlivedatacrudapp.data.model.Scientist;

Step 2: Create a RoomDatabase class

Create an abstract class and make it extend androidx.room.RoomDatabase:

public abstract class MyRoomDB extends RoomDatabase {

Step 3: Annotate it with @Database

Then annotated with @Database decoration:

@Database(entities = {Scientist.class}, version = 2, exportSchema = false)

In the above we have specified our entities, database version and whether to export schema.

Step 4: Create Factory Method

public abstract ScientistDAO scientistsDAO();

    private static MyRoomDB instance;

    public static MyRoomDB getInstance(Context con) {
        if (instance == null) {
            instance = Room.databaseBuilder(con, MyRoomDB.class,
                    "MyRoomDB")
                    .fallbackToDestructiveMigration()
                    .build();
        }
        return instance;
    }

Full Code

Here is the full code:

package info.camposha.roomlivedatacrudapp.database;

import android.content.Context;

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

import info.camposha.roomlivedatacrudapp.data.dao.ScientistDAO;
import info.camposha.roomlivedatacrudapp.data.model.Scientist;

@Database(entities = {Scientist.class}, version = 2, exportSchema = false)
public abstract class MyRoomDB extends RoomDatabase {

    public abstract ScientistDAO scientistsDAO();

    private static MyRoomDB instance;

    public static MyRoomDB getInstance(Context con) {
        if (instance == null) {
            instance = Room.databaseBuilder(con, MyRoomDB.class,
                    "MyRoomDB")
                    .fallbackToDestructiveMigration()
                    .build();
        }
        return instance;
    }
}
//end

Now move over to the next class.

Leave a Reply

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

Rating

Not enough ratings to display
X