Android Room Persistence Library: Introduction

Magda Miu
Magda Miu
Jun 2, 2017 · 3 min read

Step 1: add the dependencies in gradle

ext {
buildToolsVersion = "25.0.2"
supportLibVersion = "25.3.1"
archRoomVersion = "1.0.0-alpha1"
}

allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}
//room persistence library
compile 'android.arch.persistence.room:runtime:' + rootProject.archRoomVersion;
annotationProcessor 'android.arch.persistence.room:compiler:' + rootProject.archRoomVersion;

Step 2: create an entity

package com.magdamiu.roompersistencelibrary.entity;

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

/**
* Created by magdamiu on 30/05/17.
*/

@Entity(tableName = "Country")
public class Country {

@PrimaryKey(autoGenerate = true)
private int countryId;

@ColumnInfo(name = "name")
private String name;

@ColumnInfo(name = "town")
private String town;

public int getCountryId() {
return countryId;
}

public void setCountryId(int countryId) {
this.countryId = countryId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getTown() {
return town;
}

public void setTown(String town) {
this.town = town;
}
}

Step 3: create the DAO class

package com.magdamiu.roompersistencelibrary.dao;

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 com.magdamiu.roompersistencelibrary.entity.Country;

import java.util.List;

/**
* Created by magdamiu on 30/05/17.
*/

@Dao
public interface CountryDao {

@Query("SELECT * FROM Country")
List<Country> getAll();

@Query("SELECT * FROM Country where name LIKE :name")
Country findByName(String name);

@Query("SELECT COUNT(*) from Country")
int countCountries();

@Insert
void insertAll(Country... countries);

@Delete
void delete(Country country);
}

Step 4: create an instance of the database using Singleton

package com.magdamiu.roompersistencelibrary.database;

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

import com.magdamiu.roompersistencelibrary.dao.CountryDao;
import com.magdamiu.roompersistencelibrary.entity.Country;

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

private static AppDatabase INSTANCE;

public abstract CountryDao countryDao();

public static AppDatabase getAppDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "country-database")
// allow queries on the main thread.
// Don't do this on a real app! See PersistenceBasicSample for an example.
.allowMainThreadQueries()
.build();
}
return INSTANCE;
}

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

Step 5: test the implementation in a DatabaseInitializer class

package com.magdamiu.roompersistencelibrary.utils;

import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;


import com.magdamiu.roompersistencelibrary.database.AppDatabase;
import com.magdamiu.roompersistencelibrary.entity.Country;

import java.util.List;


public class DatabaseInitializer {

private static final String TAG = DatabaseInitializer.class.getName();

public static void populateAsync(@NonNull final AppDatabase db) {
PopulateDbAsync task = new PopulateDbAsync(db);
task.execute();
}

public static void populateSync(@NonNull final AppDatabase db) {
populateWithTestData(db);
}

private static Country addCountry(final AppDatabase db, Country country) {
db.countryDao().insertAll(country);
return country;
}

private static void populateWithTestData(AppDatabase db) {
Country country = new Country();
country.setName("France");
country.setTown("Paris");
addCountry(db, country);

List<Country> countryList = db.countryDao().getAll();
Log.d(DatabaseInitializer.TAG, "Rows Count: " + countryList.size());
}

private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {

private final AppDatabase mDb;

PopulateDbAsync(AppDatabase db) {
mDb = db;
}

@Override
protected Void doInBackground(final Void... params) {
populateWithTestData(mDb);
return null;
}
}
}

Step 6: call the implemented methods that populate the database

package com.magdamiu.roompersistencelibrary;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.magdamiu.roompersistencelibrary.database.AppDatabase;
import com.magdamiu.roompersistencelibrary.utils.DatabaseInitializer;

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getName();

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

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

public void btnSaveData_onClick(View view){
DatabaseInitializer.populateAsync(AppDatabase.getAppDatabase(this));
}
}

Magda Miu

Written by

Magda Miu

Android Google Developer Expert, CSM, CSPO ★ Trainer & Speaker ★ Blogger

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