5.3 Rooms

But what if we want to store more complex data structures? Sure you could find a way to hackily do that using SharedPreferences, but doing so can introduce bugs and is generally poor style. Android's solution is the Room library.

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

To start, you must add the following dependencies into your app's Build.gradle file:

apply plugin: "kotlin-kapt"

dependencies { 
    implementation "androidx.room:room-runtime:$room_version"
    implementation "android.arch.persistence.room:runtime:1.0.0"
    annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
    implementation "androidx.legacy:legacy-support-v4:1.0.0"
    kapt "androidx.room:room-compiler:$room_version"
}

And the following to your Project's Build.gradle:

buildscript {
  ext.room_version = '2.1.0-alpha01'
}

There are three major components in Room:

  • Data entities that represent tables in your app's database.

  • Data access objects (DAOs) that provide methods that your app can use to query, update, insert, and delete data in the database.

  • The database class that holds the database and serves as the main access point for the underlying connection to your app's persisted data.

The database class provides your app with instances of the DAOs associated with that database. In turn, the app can use the DAOs to retrieve data from the database as instances of the associated data entity objects. The app can also use the defined data entities to update rows from the corresponding tables, or to create new rows for insertion. Figure 1 illustrates the relationship between the different components of Room.

Next, we will introduce these three components more in-depth!

Last updated