Android Room Persistence Library: Introduction

The past weeks, at Google I/O 2017, the Android team lunched Room Persistence Library, a SQLite object mapper, an ORM just like greenDAO and ORMlite.

Image for post
Image for post

In the next example we will create a simple project able to manage countries, with name and town. The full source code can be found here.

project level

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

allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}

module level

//room persistence library
compile 'android.arch.persistence.room:runtime:' + rootProject.archRoomVersion;
annotationProcessor 'android.arch.persistence.room:compiler:' + rootProject.archRoomVersion;
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;
}
}
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);
}
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;
}
}
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;
}
}
}
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));
}
}

For more details about components in Room you could check this article:

Resources:

Written by

Squad Lead Developer @orangeromania ✨ Android @GoogleDevExpert ✨ Blogger, Speaker, Trainer #android #kotlin #gde #agile #scrum

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store