If your app handles non-trivial amounts of structured data, you can benefit greatly from persisting that data locally. The most common use case is to cache relevant pieces of data so that when the device can't access the network, you can still browse that content while you're offline.
The Room persistence library provides an abstraction layer over SQLite to let you access the database fluently while harnessing the full power of SQLite.
Set up Room 2.x
To use Room 2.x in your app, add the following dependencies to your app's
build.gradle file:
dependencies {
val room_version = "2.6.1"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
// To use Kotlin Symbol Processing (KSP)
// ksp("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$room_version")
// optional - RxJava2 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")
// optional - Test helpers
testImplementation("androidx.room:room-testing:$room_version")
}
Primary components
Room has three major components:
- Database class that holds the database and serves as the main access point for the underlying connection to your app's persisted data.
- Data entities that represent tables in your app's database.
- Data access objects (DAOs) that provide methods your app can use to query, update, insert, and delete data in the database.
Figure 1 illustrates the relationship between the different components of Room.
Sample implementation
// Entity
@Entity
data class User(
@PrimaryKey val uid: Int,
@ColumnInfo(name = "first_name"