Persistence being a vital part of an application as you don’t want your users local data to be lost when they close your application. It only results in poor app experience. But a library called Room, built on top of traditional SQLite provides more robust and efficient way to store and retrieve that local data in a relational form.
An Android app using Room, also allows a user to access previously cached data that was stored when network was available. So, next time when the app is accessed in the absence of network, stored data in app’s Room Database can be viewed. Although, some constraints may be applicable on accessing that offline data as defined by the makers of the application.
To add Room functionality in Android your app, add the following necessary dependencies to your app’s build.gradle
file:
dependencies {
implementation "androidx.room:room-runtime:2.6.1"
annotationProcessor "androidx.room:room-compiler:2.6.1"
// To use Kotlin annotation processing tool (kapt)
kapt "androidx.room:room-compiler2.6.1"
// To use Kotlin Symbol Processing (KSP)
ksp "androidx.room:room-compiler:2.6.1"
}
Once, you have enabled Room in app, you need to define certain Entities that’ll act as our data. For instance, Indian Railways trains can be classified via train numbers and their train names. Since each train number is unique, we can brand it as Primary Key. That train number will act as uniquely identifying data.
@Entity
data class Train(
@PrimaryKey (name = "train_Number") val trainNumber : String?,
@ColumnInfo(name = "train_Name") val trainName: String?
)
Then we can define Data Access Objects which consists of the methods to access, update, delete and insert in that relational table for that entity, which is our case is Train
. Pay close attention to the annotations of the methods. The Room compiler identifies which method it is intend for which database operation, via the annotations for which kapt
dependency is added.
@Dao
interface TrainDao {
@Query("SELECT * FROM trains")
fun getAll(): List<Train>
@Insert
fun insertAll(vararg trains: Train)
@Delete
fun delete(train: Train)
}
Now, that data and data accessing rules have been established. We can lay the ground work of centralized database definition of the app.
@Database(entities = [Train::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun trainDao(): TrainDao
}
And voila, just like that, your app is now Room equipped. Next, we’ll learn how to access and handle complex queries for database.
Leave a Reply