Room Database
This lesson will introduce how to use Room database to store and access blog articles.
We'll cover the following...
Dependencies #
To use the Room database, we need to add it to our dependencies list:
Press + to interact
dependencies {implementation 'androidx.appcompat:appcompat:1.1.0'implementation 'androidx.constraintlayout:constraintlayout:1.1.3'implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'implementation 'com.google.android.material:material:1.1.0-alpha10'implementation 'com.github.bumptech.glide:glide:4.10.0'implementation 'com.squareup.okhttp3:okhttp:4.2.1'implementation 'com.google.code.gson:gson:2.8.6'def room_version = "2.2.3"implementation "androidx.room:room-runtime:$room_version"annotationProcessor "androidx.room:room-compiler:$room_version"}
Because Room database heavily relies on custom annotations, we also added Room annotationProcessor
dependency.
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). Doing so, we tell the 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). ...