Table of Contents
What a nice room!
Room is an ORM which runs on Android and persists its data into an sqlite database.
Gradle
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
DAO is short for data access object
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface PracticeDao {
@Query("SELECT * FROM practice_session")
fun getAll(): List<PracticeSession>
@Insert
fun insert(drink: PracticeSession)
}
RoomDatabase
@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.
@Volatile
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(
context.applicationContext,
AppDatabase::class.java,
"practice_session"
).allowMainThreadQueries().build()
INSTANCE = instance
// return instance
instance
}
}
}
}
Own application class
tbd
Hint: Database Inspector is now called App Inspection
Hint 2: just works with API Level >= 26
Hint 3 Action -> Navigate to database folder
https://developer.android.com/codelabs/basic-android-kotlin-training-intro-room-flow#0






