Room Database from Google – A Simple Example

By | August 6, 2018

Lets talk about the Room Persistent Library from Google.

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

The library helps you create a cache of your app’s data on a device that’s running your app. This cache, which serves as your app’s single source of truth, allows users to view a consistent copy of key information within your app, regardless of whether users have an internet connection.

You can follow this link if you want to read more.

Let’s start…

Adding Dependencies

Open build.gradle and add these dependencies.

compile 'android.arch.persistence.room:runtime:' + rootProject.archRoomVersion;
annotationProcessor 'android.arch.persistence.room:compiler:' + rootProject.archRoomVersion;

Database

First we will create a java file named “AppDatabase.java” which extends RoomDatabase and manages the database object.


package room_db_demo.coderzheaven.com.roomdbdemo;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;

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

    private static AppDatabase INSTANCE;

    public abstract UserDao userModel();

    public static AppDatabase getInMemoryDatabase(Context context) {
        if (null == INSTANCE) {
            INSTANCE = Room.databaseBuilder(context,
                            AppDatabase.class, "MyTestDB").build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

Database Object

We will create a database object named User which is a representation of the table in the database.

User


package room_db_demo.coderzheaven.com.roomdbdemo;

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;

@Entity
public class User {
    @PrimaryKey
    @NonNull
    public String id;

    public String name;

    public String lastName;

    public int age;
}

Database Access Object

The DAO class which handles the sqlite table operations.


package room_db_demo.coderzheaven.com.roomdbdemo;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;

import java.util.List;

import static android.arch.persistence.room.OnConflictStrategy.IGNORE;
import static android.arch.persistence.room.OnConflictStrategy.REPLACE;

@Dao
public interface UserDao {
    @Query("select * from user")
    List<User> loadAllUsers();

    @Query("select * from user where id = :id")
    User loadUserById(int id);

    @Query("select * from user where name = :firstName
                                and lastName = :lastName")
    List<User> findUserByNameAndLastName(
                       String firstName, String lastName);

    @Insert(onConflict = IGNORE)
    void insertUser(User user);

    @Delete
    void deleteUser(User user);

    @Query("delete from user where name
              like :name OR lastName like :name")
    int deleteUsersByName(String name);

    @Insert(onConflict = REPLACE)
    void insertOrReplaceUsers(User... users);

    @Delete
    void deleteUsers(User user1, User user2);

    @Query("DELETE FROM User")
    void deleteAll();

}

Implementation

The Activity class which implements the room database.
We need to handle all database operations in a separate thread.

package room_db_demo.coderzheaven.com.roomdbdemo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static String TAG = "RoomDB";
    private AppDatabase mDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                mDb = AppDatabase.
                        getInMemoryDatabase(getApplicationContext());

                mDb.userModel().deleteAll();

                // Inserting Sample Data...
                DBIntializer.addUser(mDb, "1", "Coderz", "Heaven", 30);
                DBIntializer.addUser(mDb, "2", "John", "Doe", 40);
                DBIntializer.addUser(mDb, "3", "Bill", "Gates", 50);
                DBIntializer.addUser(mDb, "4", "Steve", "Jobs", 50);
                DBIntializer.addUser(mDb, "5", "Test", "User", 65);

                // Listing Users
                listUsers();

                Log.i(TAG, "Deleting User 2...");
                User user = new User();
                user.id = "2";
                mDb.userModel().deleteUser(user);
                listUsers();

                Log.i(TAG, "Deleting 2 users...");
                // Delete Users
                User user1 = new User();
                user1.id = "3";

                User user2 = new User();
                user2.id = "4";

                mDb.userModel().deleteUsers(user1, user2);
                listUsers();

                Log.i(TAG, "Replacing User 1...");
                // Inserting Or Replace an Existing User
                User newUser = new User();
                newUser.id = "1";
                newUser.name = "Coderz";
                newUser.lastName = "Heaven, India";

                mDb.userModel().insertOrReplaceUsers(newUser);
                listUsers();

                Log.i(TAG, "Deleting user by name Test...");
                // Delete a user by name...
                mDb.userModel().deleteUsersByName("Test");
                listUsers();
            }
        });

    }

    private void listUsers() {
        List<User> users = mDb.userModel().loadAllUsers();
        Log.i("Room", "Number of Users: " + users.size());
        for (User user : users) {
            Log.i(TAG, "\nId: " + user.id + ", Name: " + user.name +
                 ", LastName: " + user.lastName + ", Age: " + user.age);
        }
    }

    @Override
    protected void onDestroy() {
        AppDatabase.destroyInstance();
        super.onDestroy();
    }
}

You will be able to see the below logs once you run the application.

	I: Number of Users: 5
	I: Id: 1, Name: Coderz, LastName: Heaven, Age: 30
	I: Id: 2, Name: John, LastName: Doe, Age: 40
	I: Id: 3, Name: Bill, LastName: Gates, Age: 50
	I: Id: 4, Name: Steve, LastName: Jobs, Age: 50
	I: Id: 5, Name: Test, LastName: User, Age: 65
	I: Deleting User 2...
	I: Number of Users: 4
	I: Id: 1, Name: Coderz, LastName: Heaven, Age: 30
	I: Id: 3, Name: Bill, LastName: Gates, Age: 50
	I: Id: 4, Name: Steve, LastName: Jobs, Age: 50
	I: Id: 5, Name: Test, LastName: User, Age: 65
	I: Deleting 2 users...
	I: Number of Users: 2
	I: Id: 1, Name: Coderz, LastName: Heaven, Age: 30
	I: Id: 5, Name: Test, LastName: User, Age: 65
	I: Replacing User 1...
	I: Number of Users: 2
	I: Id: 5, Name: Test, LastName: User, Age: 65
	I: Id: 1, Name: Coderz, LastName: Heaven, India, Age: 0
	I: Deleting user by name Test...
	I: Number of Users: 1
	I: Id: 1, Name: Coderz, LastName: Heaven, India, Age: 0

Source Code

You can download the complete Android Studio source code from here.

Leave a Reply

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