Persistence Layer
Personal Catalogue: Android (Kotlin & Compose)
Course 1 ยท Chapter 3 ยท DAOs, Database, Repository and Hilt
Chapter 2 described the data; this chapter makes it real. You will add Room to the project, write the DAOs (the interfaces that hold your queries), build the database class, seed the four item types, put a repository in front of it all, and wire the pieces together with Hilt. By the end the app can store and load a catalogue, though nothing on screen uses it until Chapter 4.
androidx.room packages, which Chapter 2 and this chapter use) and the newer Room 3.0, whose packages are androidx.room3, which requires KSP and changes
some APIs. A new project today might be offered either. This course is written against Room 2.x; if you choose Room 3, the ideas are the same but every androidx.room import,
the artifact names and some signatures change, and you should follow Google's migration page (linked at the end).
Where This Layer Sits
| Layer | Android class | Web catalogue equivalent |
|---|---|---|
| Tables | Entities (Chapter 2) | Django models |
| Queries | DAO interfaces | ORM queries, Item.objects.filter() |
| Connection | RoomDatabase subclass | The database connection and settings |
| Business rules | Repository class | A service or model-manager layer |
| Wiring | Hilt modules | Dependency setup in the framework (settings.py, app factory) |
The spec's rule is one repository class between the UI and the database. Screens (Chapter 4 onward) will talk only to the repository, never to a DAO, which keeps the rules in one place and makes the view models testable in Chapter 10.
Adding Dependencies
Room needs a runtime library, an annotation processor, and (per Google's setup page) KSP to run that processor. room-ktx adds coroutine support, including the
withTransaction function used below. Hilt needs its own plugin, runtime and compiler, plus a Compose-aware helper for view models. Add them through the version catalog you met in Chapter 1.
The version numbers are placeholders: copy the current ones from the release pages, and make the KSP version match your Kotlin version, as KSP releases are tied to Kotlin releases.
The two plugins must also be declared (with apply false) in the project-level build.gradle.kts, the same way the wizard declared the others. Then use
File > Sync Project with Gradle Files. The red underlines in Chapter 2's files should vanish; if one remains, read the sync error first.
The DAOs
A DAO (data access object) is an interface whose methods carry SQL or an annotation such as @Insert. Room writes the implementation for you at build time. Methods that read
return a Flow, which re-emits whenever the underlying tables change; that is what will keep the list screen up to date with no manual refreshing. Methods that write are suspend
functions, so they run off the main thread.
Put them in ItemDao.kt, TagDao.kt, ItemTypeDao.kt and ItemTagDao.kt (Kotlin allows several per file, but one per file is easier to find). Notice
@Transaction on the two methods that return ItemWithDetails: as Chapter 2 said, Room runs several queries to fill the type and tags, and the annotation makes them one consistent
read. Notice also that findByName compares name = :name with no case handling: because the Tag.name column was declared NOCASE in Chapter 2, SQLite should
apply that collation to the comparison, so a search for "SCI-FI" finds "sci-fi".
The Database Class
The database class lists every entity, declares a version, and exposes the DAOs. It is abstract: Room generates the concrete class.
version = 1 matters later: when you change an entity after the app is installed, you raise the version and supply a migration. While developing, uninstalling the app from the
emulator is an easy way to start from a clean database. exportSchema = true asks Room to write a JSON description of each version, which migrations and tests use; Room may warn at build
time if you have not told it where to write the files (a room.schemaLocation setting in the KSP configuration), so set one if it does.
Hilt Wiring
Something must build the one database and hand it to whoever needs it. You could write a hand-made singleton, but this course follows Android Development: Architecture & Data and uses Hilt, lightly: three small pieces.
Register the application class in AndroidManifest.xml by adding android:name=".CatalogueApplication" to the <application> tag. Without that line Hilt never
starts and the build or first launch fails with a Hilt error. @Singleton on provideDatabase is essential: opening several instances of one database file is a bug.
The Repository
The repository holds the logic that is more than a single query: saving an item and its tag links as one unit, and making sure the four item types exist. @Inject constructor lets
Hilt build it, and @Singleton keeps one copy.
The seeding function is called from the activity or a view model in Chapter 4: ensureSeeded() checks the count and inserts only when the table is empty, so it is safe on every launch. A
RoomDatabase.Callback.onCreate is the other common place to seed, but its method signature differs between Room versions (the older SupportSQLiteDatabase, the newer
SQLiteConnection, and suspend functions in Room 3), whereas this repository approach does not depend on any of them.
A subtle point in getOrCreateTag: if two tags are created at once, the second insert returns -1 because of the unique index, and the code above would then
return a tag with a wrong id. Chapter 7 tightens this by re-reading the tag after an ignored insert; for now the form creates tags one at a time, so it cannot happen.
ModelContainer replaces the database class and the DAOs, queries come from
@Query in the views, and no dependency-injection library is needed. The repository still exists to hold "save with tags" and the seeding. Android pays for flexibility with more setup; SwiftUI
pays for brevity with less control over where queries live.
Challenges
Add the dependencies and plugins, create CatalogueApplication, annotate MainActivity, register the application in the manifest, and add the database class, DAOs,
module and repository. Build the project. List every error you got and which of the setup steps each pointed to.
Add a DAO query that returns how many items have a given tag id, as a Flow<Int>, and expose it from the repository. Say which index from Chapter 2 makes it quick.
Without writing code, explain what happens if saveItem is written without db.withTransaction and the app is killed between the item insert and the tag
insert. Then explain why that cannot leave an orphan row when the transaction is used.
Chapter 3 Quick Reference
- Room needs
room-runtime,room-ktxand the compiler throughksp; Hilt needs its plugin,hilt-androidand its compiler throughksp. This course uses Room 2.x (androidx.room); Room 3 usesandroidx.room3 - DAO:
@Dao interface; reads returnFlow, writes aresuspend;@Transactionon queries returning relation classes - Database:
@Database(entities, version, exportSchema)on an abstractRoomDatabasewith one abstract function per DAO - Hilt:
@HiltAndroidAppon the Application (registered in the manifest),@AndroidEntryPointon the activity,@Module @InstallIn(SingletonComponent)with@Provides @Singleton - Repository:
@Singleton class ... @Inject constructor; the only thing screens talk to - Seeding:
ensureSeeded()inserts the four types when the table is empty - Multi-step writes go inside
db.withTransaction { }
room-runtime, room-compiler through ksp and optionally room-ktx; that Room 3.0 exists with
androidx.room3 packages, requires KSP and has different callback signatures; that the (deprecated) Hilt codelab provides the database from a SingletonComponent module with
@Singleton, and the DAO from a second @Provides function.Not checked, from general knowledge: every artifact name outside Room (
hilt-android, hilt-android-compiler, hilt-navigation-compose, the plugin
ids); that Room 2.8 still ships room-ktx with withTransaction; the NOCASE comparison in findByName; exportSchema and
room.schemaLocation behaviour; the Gradle layout for plugins; and all code, none of which was compiled. Version numbers are deliberately left as placeholders because I could not confirm a
compatible Room, Hilt, KSP and Kotlin set.
Flow as StateFlow, a LazyColumn of items,
type filter chips and an empty state.