Lesson 22: Local Storage: Introduction to Room Database
Local Storage: Introduction to Room Database
Right now, close the app and your tasks vanish — everything lives only in memory. Room gives you a real local database with almost no boilerplate.
Add the dependencies
implementation("androidx.room:room-runtime:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")
ksp("androidx.room:room-compiler:2.6.1")(You'll need the KSP plugin applied at the top of your build.gradle.kts — Android Studio will prompt you to add it.)
Define your table with an Entity
@Entity(tableName = "tasks")
data class TaskEntity(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val title: String,
val isDone: Boolean
)Define your queries with a DAO
@Dao
interface TaskDao {
@Query("SELECT * FROM tasks")
fun getAllTasks(): Flow>
@Insert
suspend fun insertTask(task: TaskEntity)
@Update
suspend fun updateTask(task: TaskEntity)
}DAO stands for Data Access Object — it's the only place SQL-like queries live in your whole app. Notice getAllTasks() returns a Flow — this means the UI automatically gets updated data any time the underlying table changes, with zero manual refresh code needed.
Tie it together with a Database class
@Database(entities = [TaskEntity::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
}Creating the database instance
val db = Room.databaseBuilder(
context,
AppDatabase::class.java,
"task-database"
).build()You'd typically create this once, at app startup, and pass it down to wherever it's needed — we'll wire this into the ViewModel properly in the next lesson.
Next: Lesson 23 — combining Room with ViewModel so tasks genuinely persist.