Here in this blog, I will explore the room database for the jetpack compose project.
Step 1: Adding Dependencies
inside libs.version.toml
[version]
roomdb="2.6.1"
[libraries]
room-ktx = { group="androidx.room", name="room-ktx", version.ref="roomdb"}
room-compiler = {group="androidx.room", name="room-compiler", version.ref="roomdb"}
Add this plugin in project level build.graddle
id("com.google.devtools.ksp") version "2.1.0-1.0.29" apply false
Add these codes in module level build.graddle
plugin{
...
id("com.google.devtools.ksp")
...
}
Next adding these dependencies
implementation(libs.room.ktx)
ksp(libs.room.compiler)
Alright lets sync the project and head on to step 2 .
Step 2: Creating an entity data class.
suppose we want to create a table so here we will create a data class where we will tell what columns are in our table and what data types they can store. Remember table name is the lowercase of the data class name. Lets do it
@Entity
data class HistoryRecord(
@PrimaryKey(autoGenerate = true)
val id : Int = 0,
@ColumnInfo(name = "title")
val title : String,
@ColumnInfo(name = "watched_at")
val watchedAt : Long
)
Remember: primary key is necessary.
Step 3 :- Now we have to create a Database Access Object (DAO) . we will create this as interface and here we will define our database operations like query.
@Dao
interface HistoryDAO{
@Query("select * from historyrecord ORDER BY watched_at DESC LIMIT 10 ")
suspend fun getRecentHistory():List<HistoryRecord>
@Insert
suspend fun addRecord(historyRecord: HistoryRecord)
}
Step 4: Next task is creating our database,
@Database(entities = [HistoryRecord::class], version = 1 )
abstract class AppDatabase : RoomDatabase() {
abstract fun historyDao(): HistoryDAO
}
Here, entities mean the tables we want to have in our database. Here our abstract class App Database is a schema for creating our database and also, we are defining a component of database historyDAO for accessing our database.
Step 5: Create the database implementation
val db = Room.databaseBuilder(
context = context,
AppDatabase::class.java,
"history"
).build()
val dao = db.historyDao()
here the third parameter is our database name "history". and also we created an object of DAO so that we can perform the database operation
Step 5: Creating our implementaions of database operations in our viewmodel
fun addHistoryRecord(
title: String
) {
val record = HistoryRecord(
title = title,
watchedAt = System.currentTimeMillis()
)
viewModelScope.launch {
dao.addRecord(record)
}
}
fun logHistory() {
viewModelScope.launch {
val records = dao.getRecentHistory()
for (record in records) {
Log.d("HISTORY", record.title)
}
}
}
Good to go !! Lets see you in next learning.
0 Comments