Room Database on Android: A Complete Guide with Entity, DAO and Database

Room Database on Android with Entity, DAO and Database

Quick answer: Room is Android's official layer over SQLite. You define an @Entity (the table), a @Dao with the queries (use suspend for writes and Flow for reads that update automatically) and a @Database class created once for the whole app. Call it through a repository from your ViewModel, and write migrations whenever the schema changes so users don't lose their data.

Almost every app needs to store something locally: a cache of API data, drafts, favorites, offline records. Room is the Jetpack library for this. It checks your SQL at compile time, maps rows to Kotlin classes and works with coroutines and Flow. This guide builds a complete example, from dependencies to migrations.

What is Room?

Room is an abstraction over SQLite, the database built into Android. Compared with using SQLite directly, it:

  • validates SQL queries when you compile, not when the app crashes;
  • converts rows into data classes for you;
  • supports suspend functions and Flow out of the box;
  • handles schema versions and migrations;
  • keeps database work off the main thread.

1. Dependencies

Room generates code with KSP. In build.gradle.kts of the app module (use the KSP version that matches your Kotlin version, and check for newer Room versions):

plugins {
    id("com.google.devtools.ksp")
}

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")
}

ksp {
    arg("room.schemaLocation", "$projectDir/schemas")
}

The schema location makes Room export a JSON description of each database version, which you commit to git and use to test migrations.

2. The Entity

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

@Entity(
    tableName = "notes",
    indices = [Index(value = ["created_at"])]
)
data class Note(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    val body: String,
    @ColumnInfo(name = "is_done") val isDone: Boolean = false,
    @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis()
)

Each instance is one row. Indexes speed up queries that filter or sort by a column.

3. The DAO

import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Dao
interface NoteDao {

    @Query("SELECT * FROM notes ORDER BY created_at DESC")
    fun observeAll(): Flow<List<Note>>

    @Query("SELECT * FROM notes WHERE id = :id")
    suspend fun getById(id: Long): Note?

    @Query("SELECT * FROM notes WHERE title LIKE '%' || :term || '%' ORDER BY created_at DESC")
    fun search(term: String): Flow<List<Note>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(note: Note): Long

    @Update
    suspend fun update(note: Note)

    @Delete
    suspend fun delete(note: Note)

    @Query("DELETE FROM notes WHERE is_done = 1")
    suspend fun deleteDone(): Int
}

Functions returning Flow emit a new list every time the table changes, so the screen updates by itself after an insert or delete. suspend functions run off the main thread; Room uses its own background executor.

4. The Database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [Note::class], version = 1, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {

    abstract fun noteDao(): NoteDao

    companion object {
        @Volatile private var INSTANCE: AppDatabase? = null

        fun get(context: Context): AppDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "app.db"
                ).build().also { INSTANCE = it }
            }
    }
}

Opening a database is expensive, so there must be only one instance for the whole app. With Hilt or Koin, provide it as a singleton instead of the companion object.

5. The Repository

class NoteRepository(private val dao: NoteDao) {

    val notes: Flow<List<Note>> = dao.observeAll()

    suspend fun add(title: String, body: String) {
        dao.insert(Note(title = title.trim(), body = body.trim()))
    }

    suspend fun toggleDone(note: Note) {
        dao.update(note.copy(isDone = !note.isDone))
    }

    suspend fun remove(note: Note) = dao.delete(note)
}

The repository is where you combine local and remote data, for example saving API results in Room and always showing what is in the database, so the app works offline.

6. Integrating with the ViewModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

class NotesViewModel(private val repo: NoteRepository) : ViewModel() {

    val notes: StateFlow<List<Note>> = repo.notes
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    fun add(title: String, body: String) {
        if (title.isBlank()) return
        viewModelScope.launch { repo.add(title, body) }
    }

    fun toggle(note: Note) = viewModelScope.launch { repo.toggleDone(note) }
}

The screen collects notes and redraws when it changes. See Kotlin coroutines and Flow on Android for how to collect it safely in an Activity or Compose.

7. Migrations: changing the schema without losing data

When you add a column or table, increase the database version and give Room a migration:

import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE notes ADD COLUMN color INTEGER NOT NULL DEFAULT 0")
    }
}

Room.databaseBuilder(context, AppDatabase::class.java, "app.db")
    .addMigrations(MIGRATION_1_2)
    .build()

For simple changes, Room can also generate the migration with @Database(version = 2, autoMigrations = [AutoMigration(from = 1, to = 2)]), as long as the schemas were exported. Avoid fallbackToDestructiveMigration() in production: it deletes and recreates the database, wiping everything the user saved. If you forget the migration, the app crashes on update with an IllegalStateException about a missing migration.

Best practices

  • One database instance for the whole app;
  • Flow for data the screen observes, suspend for one-off reads and writes;
  • Never run queries on the main thread (Room blocks it by default, and you shouldn't override that);
  • Export schemas and write migrations for every version change;
  • Use @Transaction for operations that must succeed or fail together;
  • Index the columns you filter and sort by;
  • Keep the DAO behind a repository, so the ViewModel doesn't know where data comes from.

Conclusion

Room gives Android apps a safe, typed local database with little code: an Entity for the table, a DAO for the queries, a single Database instance and migrations for every change. With Flow, the screens update automatically, and with a repository, it combines naturally with data from your API. For the network side, see consuming a REST API with Retrofit.

Frequently asked questions

Room or SQLite directly?

Room. It is the officially recommended approach, checks queries at compile time and removes most of the boilerplate.

KSP or kapt for Room?

KSP. It is much faster, and kapt is in maintenance mode.

Why does Room crash with "Cannot access database on the main thread"?

You called a non-suspend query from the main thread. Make the DAO function suspend or return a Flow.

What happens if I change an Entity without a migration?

Existing users' apps crash on update. Increase the version and add a migration or an auto-migration.

Can Room work with Jetpack Compose?

Yes. Expose the DAO's Flow as a StateFlow in the ViewModel and collect it with collectAsStateWithLifecycle().

More in Android development