Beginner’s Guide to the Room Persistence Library

  • Room is a persistence library introduced by Google in 2017 I/O Event
  • Used to save data in the local database
  • It’s part of the Android Architecture Components
  • The purpose of using Room is to make it easier to work with SQLite database objects in your app. It provides an abstraction layer over SQLite to allow for a more robust database
  • Reduces the amount of boilerplate code
  • Verifies SQL queries at compile time
  • The room can be used with RxJava, Flowable, LiveData, and Coroutines

There are 3 Major components in Room:

  • Entity
    • Representation of table
  • DAO (Data Access Objects)
    • An Interface where we put all our SQL queries
  • Database
    • Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted relational data.

Room Architecture diagram:

 

The app uses the Room database to get the data access objects, or DAOs, associated with that database. The app then uses each DAO to get entities from the database and save any changes to those entities back to the database. Finally, the app uses an entity to get and set values that correspond to table columns within the database.

To use the Room in the application, add the following configuration details in the app/build.gradle file

 

dependencies {
  def room_version = "2.2.5"

  implementation "androidx.room:room-runtime:$room_version"
  annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

  // optional - Kotlin Extensions and Coroutines support for Room
  implementation "androidx.room:room-ktx:$room_version"

  // optional - RxJava support for Room
  implementation "androidx.room:room-rxjava2:$room_version"

  // optional - Guava support for Room, including Optional and ListenableFuture
  implementation "androidx.room:room-guava:$room_version"

  // Test helpers
  testImplementation "androidx.room:room-testing:$room_version"
}

Room library is the best option to save data locally in Android applications. We can not use Room if your application is exposing the database to other applications(In this case, Use Room with Content Provider)

References: