A simple guide to using Room Persistence Library with example

Sanjay K
4 min readMar 5, 2020

Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

SETUP

The section below describes how to set up using Room.

First, make sure you have the Google Maven repository added in the build.gradle :

allprojects {
repositories {
google()
jcenter()
}
}

Next, within your app/build.gradle, add Room to your dependency list :

dependencies {
def roomVersion = "2.1.0
implementation "androidx.room:room-runtime:$roomVersion"
annotationProcessor "androidx.room:room-compiler:$roomVersion"
}

Room has three main components of Room DB :

  1. Entity
  2. Dao &
  3. Database

Let’ us discuss the three in detail.

  1. Entity :

It represents the table within the database. Room creates a table for each class, which denoted by @Entity annotation. The fields describe the columns of the table.

@Entity(tableName= "Users")   -> Using @Entity to create table Users
public class User {
...........
Other methods and variables of the class
............
}

For this example, we will only discuss primary keys and how to create the same in a table.

@PrimaryKey -> Use this annotation to create the field as a primary key and autogenerate = true if you want the value to be autogenerated every time a new data is inserted or added.

@PrimaryKey(autoGenerate = true)
private int id;

After you have completed creating a class (User.class) along with the annotation, you will have something like this :

Here, @ColumnInfo annotation with name is NOT required if you want the column name in the table to be the same as the variable name you have created.

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "Users")
public class User {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "FullName")
private String fullName;
@ColumnInfo(name = "Age")
private String age;
public User(String fullName, String age) {
this.fullName = fullName;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"fullName='" + fullName + '\'' +
", age=" + age +
'}';
}
}

2. Dao

Data Access Objects or Dao are responsible for defining the methods that allow access to the database.

Annotations we will be using,

@Dao: to define the class as Room Dao.

@Dao
interface UserDAO {

@Insert: to insert user details in the database (or Users table).

@Insert
void insertUserData(User user);

@Query: to query within the table.

@Query("SELECT * FROM Users")
List<User> getSavedUsersLists();

In the above eg we will be extracting out details of all the users present in the Users table.

After adding the annotation and creating the required methods, we will have the following interface :

import java.util.List;import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
@Dao
interface UserDAO {
@Insert
void insertUserData(User user);
@Query("SELECT * FROM Users")
List<User> getSavedUsersLists();
}

3. Database

It contains the database holder. It is an abstract class where you define all the entities that means all the tables that you want to create for that database. We define the list of operations that we would like to perform on the table.

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(entities = {User.class}, version = 1)
public abstract class UserDatabase extends RoomDatabase {
private static String DATABASE = "DemoAppDatabase";
private static UserDatabase instance;
static UserDatabase getInstance(Context context){
if(instance == null){
instance = Room.databaseBuilder(
context.getApplicationContext(),
UserDatabase.class,
DATABASE)
.allowMainThreadQueries()
.build();
}
return instance;
}
public abstract UserDAO getUserDao();
}

For the sake of simplicity and easy understanding, I have allowed creating queries on the main thread itself, but it’s not considered as the right approach. So try using a background for the queries instead this way.

Now finally, we need to make calls to the database and perform operations.

String fullName = fullNameEditText.getText().toString();
String age = ageEditText.getText().toString();
User user = new User(fullName, age);

Here above, I have successfully created a user object, and now I will add the same to the table Users.

UserDatabase userDatabase = UserDatabase.getInstance(context);
userDatabase.getUserDao().insertUserData(user);

Now to see whether our data has successfully stored or not?

List<User> userList= userDatabase.getUserDao().getSavedUsersLists();
System.out.println(userList);

Now you will see the list of users will be printed.

If you find any problem, let me know in the comment section. Also, I have attached the Github link. You can compare the code too. The code on the Github is a bit different(with more complexity, used Repository class to make database method calls), but the concept remains the same.

Source Code: Github

--

--