Implementing database in android using Room Persistence Library

Inception Development Department

Android provides a full support for SQLite databases. The recommended way to create a new SQLite database in android is to use Room persistence library. The Room persistence library adds an abstraction layer over SQLite to allow a fluent database access while harnessing the full power of SQLite.

There are three major components in Room:

Database:

Contains the database holder and serves as the main access point for underlying connection to app’s persisted data. The class is annoted with @Database and defines the list of Entities and DAOs.

Entity:

Represents a table within a database.

DAO:

Contains the  methods for accessing database.







Lets start by implementing an example for further understanding how it works. In this example we will store a user’s information such as name, age, gender etc. Here are the steps to add Room in an android project.

1  Create a new android project with an empty activity.

2   Add the google maven repository

To add this, open build.gradle file in the project (not the ones for app or module) and add the following highlighted text.

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

3  Add dependencies for Room

Open build.gradle for app or module and add following dependencies

dependencies {
//dependency for Room persistence library
//dependency for Room persistence library
      implementation "android.arch.persistence.room:runtime:1.0.0"
      annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
}

4  Now, lets create an Entity called User. It defines attributes for user table in database. The class is annoted with @Entity and it must contain a Primary key field which is annoted with @PrimaryKey. A primary key can be generated automatically by adding a property aotoGenerate to @PrimaryKey. The User Entity looks like this:

@Entity(tableName = "user")  // add tableName to change the default table name
public class User {
  @PrimaryKey(autoGenerate = true)
  private int uid;
  @ColumnInfo(name = "name")
  private String name;
  @ColumnInfo(name = "age")
  private int age;
  public int getUid() {
      return uid;
  }
  public void setUid(int uid) {
      this.uid = uid;
  }
  public String getName() {
      return name;
  }
  public void setName(String name) {
      this.name = name;
  }
  public int getAge() {
      return age;
  }
  public void setAge(int age) {
      this.age = age;
  }
}

4  To create a Database Access Object (DAO), create an interface UserDao with annotation @Dao. There are four annotations @Query, @Insert, @Update and @Delete to perform CRUD operations.

@Dao
public interface UserDao {
  @Query("SELECT * FROM user")
  List<User> getAll();
  @Query("SELECT * FROM user where name LIKE  :name")
  User findByName(String name);
  @Query("SELECT COUNT(*) from user")
  int countUsers();
  @Insert
  void insert(User user);
  @Delete
  void delete(User user);
}

5  Finally, create a database holder class MyDatabase that extends RoomDatabase and annote @Database to it. We add list of entities and database version. We will use singleton pattern to get the instance of our database as mentioned below:

@Database(entities = {User.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
  public static MyDatabase INSTANCE;
  public abstract UserDao userDao();
  public static MyDatabase getDatabase(Context context) {
      if (INSTANCE == null) {
          INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                  MyDatabase.class, "my_application").build();
      }
      return INSTANCE;
  }
  public static void destroyInstance() {
      INSTANCE = null;
  }
}

Great, at this moment Room is setup and we can add or retrieve user data from our Activity or Fragment. We should make our request in a background thread. I have used AsyncTask for this purpose. Below is the code to add a user into our database.

Private UserDao userDao;	
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(..);
MyDatabase mDb = MyDatabase.getDatabase(this);
userDao = mDb.userDao();
new SaveUserTask().execute(user);
new SaveUserTask().execute(user);
}
Private class SaveUserTask extends AsyncTask<User, Void, Void> {
  @Override
  protected Void doInBackground(User... users) {
      User user = users[0];
      userDao.save(user);
      return null;
  }
}

Congratulations, now you can use Room persistence library in you android project to implement SQLite database and I hope this blog helped you to learn and implement Room persistence library.