Android Room Persistence Library

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.

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.

Step 1: add the dependencies in gradle

  • 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;

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));
    }
}

Resources:

Advertisements
Android Room Persistence Library

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s