Dababase Stuff with Room

What a nice room!

Room is an ORM which runs on Android and persists its data into an sqlite database.


Room makes use of the kotlin annotation processing tool KAPT. So we need to apply the plugin:

plugins {
    id 'kotlin-kapt'

These are the dependencies we need to use room and kapt:

    implementation "androidx.room:room-runtime:2.3.0"
    kapt "androidx.room:room-compiler:2.3.0"

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:2.3.0"

Entity class

an entity class represents the entry which is persisted in the database

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "practice_session")
data class PracticeSession(
    @PrimaryKey(autoGenerate = true) val uid: Int = 0,
    @ColumnInfo(name = "start_time") val startTime: Long,
    @ColumnInfo(name = "stop_time") val stopTime: Long


DAO is short for data access object

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query

interface PracticeDao {
    @Query("SELECT * FROM practice_session")
    fun getAll(): List<PracticeSession>

    fun insert(drink: PracticeSession)


@Database(entities = [PracticeSession::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun practiceDao(): PracticeDao

    companion object {
        // Singleton prevents multiple instances of database opening at the
        // same time.
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                INSTANCE = instance
                // return instance

Own application class



Hint: Database Inspector is now called App Inspection

Hint 2: just works with API Level >= 26

Hint 3 Action -> Navigate to database folder