Room Library in Android Apps

Pravin Bendre
Nov 1 · 3 min read

Many of Android Apps are using SQLite Database

The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.

For Android developers to implement data storage and manipulation finds out bit time consuming as it need to write lot of code, need to write SQL queries manually, implement POJO java classes for models and queries are not verified at compile time.

Room is an ORM, Object Relational Mapping library. In other words, Room will map our database objects to Java objects. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Room vs SQLite

Room provides compile time verification of SQL queries, In other hand SQLite do not verify SQL queries at compile time.

Room provides different components so change in database schema can be handle automatically by Room. Where, in SQLite you need to change SQL queries manually.

Room has built in support for RxJava/RxAndroid and LiveData for data change observation while SQLite does not.

You need to write lot of boilerplate code to change over between SQL queries and Java POJO class objects. However, Room maps your database objects to Java Object without boilerplate code.

Lets deep into Room now

Room provides three major components for seamless operations to your database. You can use these using annotations.

Do not forget to add dependencies

implementation ‘android.arch.persistence.room:runtime:1.1.1’
annotationProcessor ‘android.arch.persistence.room:compiler:1.1.1’

Entity, Dao and Database lets discuss more specific

Database

To be a main database class it should follow conditions.

First, It should be annotated with @Database entry.

Second, should be an abstract class that extends RoomDatabase.

Third, should include the list of entities associated with the database within the annotation.

Finally, contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao .

If you comply your class to above conditions. Should be ok to access database instance at runtime by writing.

Example code

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}

This how you access database instance

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();

Entity

Room creates a table for each class annotated with @Entity; the fields in the class correspond to columns in the table. Therefore, the entity classes tend to be small model classes that do not contain any logic.

Annotate with @Entity before class definition and use the tableName property to name of the table.

Use@PrimaryKey annotation to set the primary key, make sure you assign this to your table’s unique identifier column.

Set the name of the columns for your class fields using the @ColumnInfo(name = “column_name”) annotation. Feel free to skip this step if your fields already have the correct column name.

If multiple constructors are suitable, use @Ignore annotation to constructors those are no need to execute at first place.

Example code

@Entity
public class User {
@PrimaryKey
public int uid;

@ColumnInfo(name = "first_name")
public String firstName;

@ColumnInfo(name = "last_name")
public String lastName;
}

DAO interface

Dao, data access objects. It would be responsible for declaring methods that are accessing database.

This interface should be annotated with @Dao.

There are four annotations @Query, @Insert, @Update, @Delete to perform CRUD operations. @Query is used to perform Select operation on the database.

Example code

@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();

@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);

@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
User findByName(String first, String last);

@Insert
void insertAll(User... users);

@Delete
void delete(User user);
}

Final say

We get compile-time verification of SQL queries, So there is no more syntax errors at runtime.

- Very less code to write

- Support to integrate with other Architecture components

That’s all, hope this will help you.

Thank you!

Where to go from here!

You can take look at here!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade