Room Database

Android Development with Compose: Architecture & Data

Course 5 ยท Chapter 4 ยท A Real Database

Until now the notes lived in a fake list that vanished when the app closed. Room is Android's library for keeping data in a local SQLite database without writing the plumbing by hand. You describe a table as a class (an entity), the queries as an interface (a DAO), and the database as a class that ties them together. Room generates the rest.

What was checked, and how: read this first
Checked in the docs (two web searches, summaries only): Room now has two lines, Room 2.x (package androidx.room) and Room 3.0 (package androidx.room3, artifacts room3-runtime and room3-compiler); Room 3.0 only supports KSP (no KAPT or Java annotation processors) and you can move to KSP while still on 2.x; DAO methods that return a Flow need not be suspend, other DAO functions must be; coroutines and Flow are built into the 2.x runtime so no extra artifact is needed; in 3.0 migrations and callbacks use SQLiteConnection instead of SupportSQLiteDatabase; and the docs recommend moving first to Room 2.8 with KSP and coroutines, then to 3.0. Not checked: the KSP plugin id and version rules, the code below (written in the long-standing Room 2.x form), and anything about the 3.0 database-builder call. I could not confirm which Room version is the current stable one (the release page showed 3.0.3 while another docs page used a 3.1.0 alpha as an example), so every version here is a placeholder. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.

Which Room? 2.x or 3.0

Room 2.xRoom 3.0 (docs)
Packageandroidx.roomandroidx.room3
Artifactsroom-runtime, room-compilerroom3-runtime, room3-compiler
Code generationKSP (KAPT also worked in older versions)KSP only
DAO functionsSuspend for one-shot calls, Flow for observingSame rule: suspend unless the return type is observable
MigrationsSupportSQLiteDatabaseSQLiteConnection
Other reactive types (LiveData, RxJava, Paging)SupportedNeed registered @DaoReturnTypeConverters from their own artifacts

How this chapter handles it. The code below uses the long-standing Room 2.x form, with androidx.room imports. (docs) Moving to 3.0 is described as mostly a rename of artifacts and imports plus the migration changes above, and the recommended route is to get onto Room 2.8 with KSP and coroutines first. Before you start a real project, read the current Room release notes and the migration guide and pick one line; if you pick 3.0, change the imports to androidx.room3 and check the database builder against the migration guide, because that part was not checked here.

Setup

// Room 2.x: module build.gradle.kts (versions are placeholders) plugins { id("com.google.devtools.ksp") version "<ksp-version>" } dependencies { implementation("androidx.room:room-runtime:<room-version>") ksp("androidx.room:room-compiler:<room-version>") }
// Room 3.0: the artifacts and the package are renamed (check the current version) dependencies { implementation("androidx.room3:room3-runtime:<room-version>") ksp("androidx.room3:room3-compiler:<room-version>") }
  • (docs) The compiler dependency goes through ksp, not kapt. (docs) No separate coroutines artifact is needed for Room 2.x.
  • (general knowledge) The KSP plugin id com.google.devtools.ksp and the need to match its version to your Kotlin version. The generated project uses AGP 9.x and Kotlin 2.2 (Android Studio 2: The New UI 4), so take the matching KSP version from the KSP release notes; with a version catalog you would write the plugin and libraries there instead.

An Entity: One Row, One Class

import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "notes") data class NoteEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val text: String, val createdAt: Long = System.currentTimeMillis() )
  • @Entity makes the class a table; @PrimaryKey(autoGenerate = true) lets the database number the rows (general knowledge).
  • It is a storage class. The UI will use a separate model, mapped from this one in Chapter 5, so a change to the table does not ripple through the screens.

A DAO: The Questions You Can Ask

import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface NoteDao { // A Flow: emits the list now and again whenever the table changes. Not suspend. @Query("SELECT * FROM notes ORDER BY createdAt DESC") fun observeNotes(): Flow<List<NoteEntity>> // One-shot writes are suspend functions @Insert suspend fun insert(note: NoteEntity) @Delete suspend fun delete(note: NoteEntity) @Query("DELETE FROM notes") suspend fun clearAll() }

(docs) A Flow-returning query emits again whenever the data changes, and does not need suspend. Writes are suspend functions, which Room runs off the main thread for you (general knowledge), so they are main-safe in the sense of Chapter 3. Room checks the SQL in each @Query when it compiles, so a typo in a column name fails the build rather than the app (general knowledge).

The Database Class

import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [NoteEntity::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao }
import android.app.Application import androidx.room.Room class NotesApp : Application() { // One database for the whole app val database: AppDatabase by lazy { Room.databaseBuilder( applicationContext, AppDatabase::class.java, "notes.db" ).build() } } // AndroidManifest.xml: <application android:name=".NotesApp" ... >

(general knowledge) version is the schema version. Change an entity and you must raise it and provide a migration, or the existing database on a user's phone cannot be opened. exportSchema = false keeps this chapter simple; real apps export schemas to track changes, which the docs cover under migrations. Build one database for the whole app, not one per screen.

A Search Query With a Parameter

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

(general knowledge) :term refers to the function's parameter; Room binds it safely, so user text is never pasted into the SQL.

Testing a DAO

(general knowledge) The usual test builds an in-memory database that vanishes when closed, and checks a query against it. Android Development with Compose: Production & Publishing (planned) covers testing properly; here is the shape, which also needs the AndroidX test and coroutines-test libraries:

// app/src/androidTest/.../NoteDaoTest.kt class NoteDaoTest { private lateinit var db: AppDatabase private lateinit var dao: NoteDao @Before fun createDb() { val context = ApplicationProvider.getApplicationContext<Context>() db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build() dao = db.noteDao() } @After fun closeDb() = db.close() @Test fun insertedNoteIsObserved() = runTest { dao.insert(NoteEntity(text = "Buy milk")) val notes = dao.observeNotes().first() assertEquals(listOf("Buy milk"), notes.map { it.text }) } }
Compared with the Classic UI course
Android Development: Architecture & Data 3 teaches entities, DAOs, the database class and coroutines with Room, with the annotation processor set up through kapt in the older edition. The idea is the same. Now the compiler runs through ksp, a Flow from the DAO replaces LiveData, and Room 3.0 is a real choice you have to make.

Try It Yourself

Exercise 1

Add the dependencies, NoteEntity, NoteDao and AppDatabase to a project and build it. Report the Room and KSP versions you used, where you found them, and any build error. A Room compile error often means a typo in an annotation or query.

๐Ÿ“„ View solution
Exercise 2

Add the search query to the DAO. Then say what must change if you add a pinned: Boolean column to NoteEntity after the app has already been installed on a phone.

๐Ÿ“„ View solution
Exercise 3

Write the in-memory DAO test from the chapter, add the test dependencies it needs, and run it. Report whether it passed, and what you had to add that the chapter did not mention.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (two web searches, summaries only): the Room 2.x and Room 3.0 lines and their package and artifact names; KSP only in 3.0 and usable from 2.x; the DAO suspend and Flow rule; no extra coroutines artifact in 2.x; SQLiteConnection migrations in 3.0; the recommended two-step path through Room 2.8; the existence of @DaoReturnTypeConverters for other reactive types.
General knowledge, not checked: the KSP plugin id and version matching; @Entity, @PrimaryKey, @Insert, @Delete and the database builder as shown; that Room checks SQL at compile time and runs suspend writes off the main thread; exportSchema; the in-memory test.
Not verified: which Room version is the current stable one (placeholders are used); the Room 3.0 database-builder call; every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: Room 3.0 releases (developer.android.com), Migrate from Room 2.x to Room 3.0 (developer.android.com), Access data using Room DAOs (developer.android.com), Write asynchronous DAO queries (developer.android.com), Persist data with Room codelab (developer.android.com), Room 3.0: Modernizing the Room (Android Developers Blog).
Coming up
Chapter 5 puts a repository in front of the DAO: one source of truth for the notes, mapping NoteEntity to the model the UI uses, and replacing Chapter 3's fake repository.