Search⌘ K
AI Features

Room Database

Explore how to use the Room database in Android apps to create entities, build DAOs, and enable offline support with efficient data caching. Learn to define database tables, handle embedded objects, and implement data access methods to manage blog data in Kotlin.

We'll cover the following...

Dependencies

To use the Room database, we need to add it to our dependencies list:

Shell
dependencies {
// kotlin
implementation "androidx.core:core-ktx:1.6.0"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// http
implementation 'com.squareup.okhttp3:okhttp:4.2.1'
implementation 'com.google.code.gson:gson:2.8.6'
// ui
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.android.material:material:1.3.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
// database
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
}

Because the Room database heavily relies on custom annotations, we also added the Kotlin annotation processor (kapt) dependency.

Shell
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-parcelize'
apply plugin: 'kotlin-kapt'

Entities

Now, we need to tell Room what entities we want to save to the database. Let’s open the Blog class and add the @Entity annotation (1). In doing so, we tell Room to create a table for the blog entity.

To define a primary key, we can simply use @PrimaryKey annotation on the id field (2). While the Room library can automatically persist all Kotlin primitives, it can’t persist custom objects, like Author. To save the Author object, we have two options:

  • Create a table for
...