Room — Getting Started

Google stepped up at I/O with a suite of Architecture Components. One of them being Persistence Library called Room. This is an abstraction layer over SQLite, providing Object mapping, and other good stuff.


We’re going Kotlin in this tutorial, and RXJava, sorry; not sorry…

Step 1: Gradle

Obviously these versions will change, so go check maven for the latest.

Step 2: Creating an Entity

The Entity is our model, there are various annotations we can use. For simplicity I’ve just used a PrimaryKey annotation.

Step 3: Create the DAO (Data Access Object)

Here’s where it gets interesting.. with the power of Annotations. The @Insert function … thats it.. just supply the object. Done. Some may not like the fact that you need to write SQL queries, but at least these are compile time safe. Spell person wrong, and no build for you. Its a very Retrofit-y approach, and thats Good.

Note: This is similar to SQL Delight by Square, but not quite as good as that tells you before compile!

Step 4: Create the Room Database

Right time to swap Retrofit for Dagger .. This reeks of a Dagger Component, again not a bad thing.

Here we setup the entities, and Dao’s, very straight forward.

Step 5: Setup the Database

It is recommended that we use a Singleton pattern when using Room. My personal preference would be to set this up using Dagger. But.. for simplicity we’ll just set one up in the Application.

Again, a pretty straightforward API to create a Room database, supplying your database class, and a name that will be used as the name of the sqlite database created.

Step 6: Insert some data

A really simple call

Joan Gotcha!!!!

This is going to throw an exception for accessing on the main thread .. yay!

Step 7: Really, lets insert some data

Ok, lets throw some RX at the problem for a quick win.

That’s it, just call the insert method on the Dao. Because we set the uid to be autoGenerate, just supply a zero and the db will take care of it.

Step 8: Retrieve data

For this part, I decided to use an RX Observable to constantly get updates. Now as soon as the Person table is updated, we get all people delivered.

That’s a very basic overview for now.

Next up Entity Annotations