Backup, Tests and Next Steps

Personal Catalogue: Android (Kotlin & Compose)

Course 1 ยท Chapter 10 ยท JSON Backup, Tests and the Road Ahead

The last item on the spec's essential list is backup, and it matters more than it sounds. The catalogue lives only on one phone, in a database no one else can read. Lose the phone, or clear the app's storage, and years of careful cataloguing are gone. This chapter lets the user export everything to a JSON file they choose the location of, and import it back. Then it adds tests, so the rules you have built are protected when you change things later, and ends with where the app could go next.

What was run, and what was not
Nothing was compiled or run (no Android Studio here), and no test in this chapter has been executed. Two searches were made. The first confirmed the Storage Access Framework rules (the user picks the file with ACTION_CREATE_DOCUMENT or ACTION_OPEN_DOCUMENT, which gives your app access to just that file) and the Compose launcher pattern, but did not show openOutputStream used with those results, so that call is from memory. The second confirmed the in-memory-database approach to testing Room, but the Room testing page describes newer setups (BundledSQLiteDriver, JVM tests) that I have not followed: the tests here use the long-established instrumented pattern, so check the page for your Room version.

Where We Are

Spec itemBuilt in
1. Add, edit, delete, labels per typeChapters 5 and 6
2. List, newest first, type filterChapters 4 and 8
3. Detail screenChapter 5
4. Managed tagsChapters 2, 3 and 7
5. Search and tag filterChapter 8
6. Duplicate warningChapter 9
7. Local storage, offlineChapters 2 and 3
8. Light and dark theme, empty states, accessibilityChapters 4, 8 and 9
9. Backup: export and import JSONThis chapter

Part 1: A Backup Format

A backup file must outlive the database it came from, so it must not contain database ids. Row ids are an accident of one install; if you restore into a fresh database the ids differ. Instead the file stores an item's type and tags by name, and the importer looks them up again. It also carries a version number, so a future app that adds fields (Part 5) can still read old files, and can refuse files from a future version it does not understand. You already added the Kotlin serialization plugin and library in Chapter 5; the same library encodes and decodes JSON.

package com.example.catalogue.backup import com.example.catalogue.data.ItemWithDetails import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json @Serializable data class BackupFile( val version: Int = CURRENT_VERSION, val exportedAt: Long, val items: List<BackupItem> ) { companion object { const val CURRENT_VERSION = 1 } } @Serializable data class BackupItem( val title: String, val creator: String = "", val formatDetail: String = "", val releaseYear: Int? = null, val notes: String = "", val createdAt: Long, val type: String, // "Book", "CD", ... by name, not id val tags: List<String> = emptyList() ) val backupJson = Json { prettyPrint = true // a human can open and read the file encodeDefaults = true ignoreUnknownKeys = true // tolerate fields added by a newer version } fun ItemWithDetails.toBackup() = BackupItem( title = item.title, creator = item.creator, formatDetail = item.formatDetail, releaseYear = item.releaseYear, notes = item.notes, createdAt = item.createdAt, type = type.name, tags = tags.map { it.name }.sorted() )

The exported file looks like ordinary JSON, which is the point: it can be read in a text editor, kept in cloud storage, or fixed by hand. Compare the web catalogues' database dumps; this is the same idea in a portable form.

Part 2: Export and Import in the Repository

Two new read queries are needed, and one to detect an item that is already present:

// ItemTypeDao @Query("SELECT * FROM item_type ORDER BY id") suspend fun getAll(): List<ItemType> // ItemDao @Transaction @Query("SELECT * FROM item ORDER BY createdAt") suspend fun getAll(): List<ItemWithDetails> @Query( """ SELECT COUNT(*) FROM item WHERE title = :title AND creator = :creator AND itemTypeId = :typeId AND createdAt = :createdAt """ ) suspend fun countExact(title: String, creator: String, typeId: Long, createdAt: Long): Int

Then two repository functions. Three design decisions are worth reading before the code:

  • Import merges; it does not replace. Existing items are never touched. An incoming item that matches an existing one on title, creator, type and creation time is skipped, so importing the same file twice does not double the catalogue. (A deliberate duplicate, Chapter 9's "I own two copies", has a different creation time, so it survives a round trip.)
  • Import is all-or-nothing. It runs in one transaction; if any item is bad, an exception rolls everything back, and the user is never left with a half-imported catalogue.
  • Unknown types are an error, not a guess. The four types are a fixed list, so an item naming another type means the file is not from this app.
data class ImportResult(val added: Int, val skipped: Int) suspend fun exportBackup(): String { val all = itemDao.getAll() return backupJson.encodeToString( BackupFile(exportedAt = System.currentTimeMillis(), items = all.map { it.toBackup() }) ) } /** Throws SerializationException for bad JSON, IllegalArgumentException for a bad backup; changes nothing then. */ suspend fun importBackup(json: String): ImportResult { val file = backupJson.decodeFromString<BackupFile>(json) require(file.version <= BackupFile.CURRENT_VERSION) { "This backup was made by a newer version of the app." } ensureSeeded() return db.withTransaction { val types = itemTypeDao.getAll().associateBy { it.name.lowercase() } var added = 0 var skipped = 0 for (b in file.items) { val type = types[b.type.lowercase()] ?: throw IllegalArgumentException("Unknown item type \"${b.type}\".") val title = b.title.trim() val creator = b.creator.trim() if (title.isEmpty() || itemDao.countExact(title, creator, type.id, b.createdAt) > 0) { skipped++ continue } val tagIds = b.tags.map { getOrCreateTag(it).id }.toSet() writeItem( Item( title = title, creator = creator, formatDetail = b.formatDetail.trim(), releaseYear = b.releaseYear, notes = b.notes.trim(), createdAt = b.createdAt, itemTypeId = type.id ), tagIds ) added++ } ImportResult(added, skipped) } }

The decoding happens before the transaction starts, so a file that is not JSON at all fails fast without touching the database. Everything after it uses the functions you already trust: getOrCreateTag (Chapter 7) keeps tag names unique, and writeItem writes the item and its links.

Part 3: The Storage Access Framework

How does the app get a place to write the file, without asking for broad storage permission? Through the Storage Access Framework. Per Google's documentation, apps go through ACTION_CREATE_DOCUMENT (save a single file) or ACTION_OPEN_DOCUMENT (open one), which require the user to pick the location or the file themselves; your app is then granted a URI permission for exactly that one document. The practical result is that you need no storage permission in the manifest, and the user keeps full control of where their backup goes (device storage, a cloud drive, an SD card).

StepExportImport
ContractActivityResultContracts.CreateDocument("application/json")ActivityResultContracts.OpenDocument()
Launchlauncher.launch("catalogue-backup.json") (suggested name)launcher.launch(arrayOf("application/json", ...)) (accepted types)
ResultA Uri (or null if cancelled)A Uri (or null if cancelled)
Your codeOpen an output stream on the Uri and write the JSONOpen an input stream on the Uri, read the text, import it
Web equivalentA "Download backup" linkA file upload form

The view model

The view model needs the application Context to reach the ContentResolver (the system service that turns a Uri into a stream); Hilt supplies it with @ApplicationContext, which is safe to hold because it lives as long as the app. Reading and writing files is slow, so it runs on Dispatchers.IO.

package com.example.catalogue.backup import android.content.Context import android.net.Uri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.catalogue.data.CatalogueRepository import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.SerializationException data class BackupUiState(val working: Boolean = false, val message: String? = null) @HiltViewModel class BackupViewModel @Inject constructor( @ApplicationContext private val context: Context, private val repository: CatalogueRepository ) : ViewModel() { private val _state = MutableStateFlow(BackupUiState()) val uiState: StateFlow<BackupUiState> = _state.asStateFlow() fun exportTo(uri: Uri) = launchWork { val json = repository.exportBackup() withContext(Dispatchers.IO) { context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(json.toByteArray(Charsets.UTF_8)) } ?: error("Could not open the file for writing.") } "Backup saved." } fun importFrom(uri: Uri) = launchWork { val text = withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() } ?: error("Could not open the file for reading.") } val result = repository.importBackup(text) "Imported ${result.added} item${if (result.added == 1) "" else "s"}; ${result.skipped} already present." } fun messageShown() = _state.update { it.copy(message = null) } private fun launchWork(block: suspend () -> String) { if (_state.value.working) return _state.update { it.copy(working = true, message = null) } viewModelScope.launch { val message = try { block() } catch (e: CancellationException) { throw e } catch (e: SerializationException) { "That file is not a catalogue backup." } catch (e: IllegalArgumentException) { e.message ?: "That backup could not be imported." } catch (e: Exception) { "Something went wrong: ${e.message ?: "unknown error"}" } _state.update { it.copy(working = false, message = message) } } } }

The catch order goes from most specific to most general, and the final message is the app's Chapter 9 philosophy again: every failure ends in a sentence the user can read, never a silent crash. Note that "wt" asks to truncate the file when writing, so an overwritten backup does not keep stale trailing bytes.

The screen

rememberLauncherForActivityResult is the Compose way to start a "go and pick something" action and receive the result; Google's documentation says it handles registering and unregistering the launcher for you. Each launcher is given a contract, and its callback receives the chosen Uri, or null if the user backed out.

package com.example.catalogue.backup import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle @OptIn(ExperimentalMaterial3Api::class) @Composable fun BackupScreen(onBack: () -> Unit, viewModel: BackupViewModel = hiltViewModel()) { val state by viewModel.uiState.collectAsStateWithLifecycle() val exportLauncher = rememberLauncherForActivityResult( ActivityResultContracts.CreateDocument("application/json") ) { uri -> if (uri != null) viewModel.exportTo(uri) } val importLauncher = rememberLauncherForActivityResult( ActivityResultContracts.OpenDocument() ) { uri -> if (uri != null) viewModel.importFrom(uri) } Scaffold( topBar = { TopAppBar( title = { Text("Backup and restore") }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") } } ) } ) { innerPadding -> Column( Modifier.padding(innerPadding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { Text( "Save your whole catalogue to a file you choose, or restore from one. " + "Restoring adds items; it never deletes or changes what is already here." ) Button( onClick = { exportLauncher.launch("catalogue-backup.json") }, enabled = !state.working, modifier = Modifier.fillMaxWidth() ) { Text("Export backup") } OutlinedButton( onClick = { importLauncher.launch(arrayOf("application/json", "text/plain", "application/octet-stream")) }, enabled = !state.working, modifier = Modifier.fillMaxWidth() ) { Text("Import backup") } if (state.working) LinearProgressIndicator(Modifier.fillMaxWidth()) state.message?.let { Text(it, style = MaterialTheme.typography.bodyLarge) } } } }

The import launcher lists several accepted types because file managers and cloud drives are inconsistent about labelling a .json file; being generous avoids a greyed-out file. The message shows in place; a snackbar would also do, as in Chapter 9.

Getting to it

Add @Serializable object BackupRoute to Routes.kt, a composable<BackupRoute> { BackupScreen(onBack = { navController.popBackStack() }) } to the NavHost, a new onBackupClick: () -> Unit parameter on ListScreen and ListContent, passed as { navController.navigate(BackupRoute) }, and an action in the list's TopAppBar:

TopAppBar( title = { Text("My Catalogue") }, actions = { IconButton(onClick = onBackupClick) { Icon(Icons.Filled.Settings, contentDescription = "Backup and restore") } } )

Try it: export, then clear the app's storage (Settings > Apps > Catalogue > Storage > Clear storage), reopen it, and import. The items, types, tags, notes and creation dates should all be back. Open the exported file in a text editor to see the JSON for yourself. The file is unencrypted plain text, so the user should store it somewhere they trust; for a shopping-list-grade catalogue that is a reasonable trade for being readable and portable.

Part 4: Tests

You now have rules that are easy to break by accident: tag names must be unique ignoring case, search patterns must escape wildcards, a backup must survive a round trip. Tests turn those rules into things the computer checks for you. There are three layers, from cheapest to most involved, and you should write them in this order:

LayerTestsWhere it runsFolder
Pure functionslikePattern, normaliseTagName, JSON round tripYour computer, in milliseconds (a local test)app/src/test/...
Repository on a real databaseSaving with tags, cascades, duplicates, importAn emulator or device (an instrumented test), with an in-memory databaseapp/src/androidTest/...
View modelSearch state, filtersSame as the repository, because it uses the real repositoryapp/src/androidTest/...

Add testImplementation for kotlinx-coroutines-test (and JUnit, which the wizard normally adds already), and androidTestImplementation for kotlinx-coroutines-test and the AndroidX test libraries; versions from the release pages, as always.

Layer 1: pure functions

package com.example.catalogue import com.example.catalogue.backup.* import com.example.catalogue.data.* import org.junit.Assert.assertEquals import org.junit.Test class PureRulesTest { @Test fun emptySearchMeansNoPattern() { assertEquals("", likePattern(" ")) } @Test fun searchWrapsInWildcards() { assertEquals("%dune%", likePattern(" dune ")) } @Test fun wildcardsInTheQueryAreEscaped() { assertEquals("%100\\%%", likePattern("100%")) assertEquals("%a\\_b%", likePattern("a_b")) assertEquals("%a\\\\b%", likePattern("a\\b")) } @Test fun tagNamesAreTrimmedAndCollapsed() { assertEquals("retro games", normaliseTagName(" retro games ")) } @Test fun backupSurvivesAJsonRoundTrip() { val original = BackupFile( exportedAt = 1_700_000_000_000, items = listOf( BackupItem(title = "Dune", creator = "Frank Herbert", releaseYear = 1965, createdAt = 1_600_000_000_000, type = "Book", tags = listOf("classic", "sci-fi")), BackupItem(title = "Emma", createdAt = 1_600_000_100_000, type = "Book") ) ) val decoded = backupJson.decodeFromString<BackupFile>(backupJson.encodeToString(original)) assertEquals(original, decoded) } }

Notice what the escaping test shows: the Kotlin string "%100\\%%" is the four-character text %100\%%. These tests would have caught the "escape the backslash first" mistake discussed in Chapter 8 immediately. Run them with a right-click on the file and Run 'PureRulesTest'.

Layer 2: the repository on an in-memory database

An in-memory database lives only for the test and vanishes with it, so every test starts clean and nothing is left on the device. Google's Room testing page recommends this for isolation, and closing the database after each test. The pattern below is the long-established instrumented one, which needs an emulator or phone.

package com.example.catalogue import androidx.room.Room import androidx.test.core.app.ApplicationProvider import com.example.catalogue.data.* import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test class RepositoryTest { private lateinit var db: AppDatabase private lateinit var repo: CatalogueRepository @Before fun setUp() { db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java).build() repo = CatalogueRepository(db, db.itemTypeDao(), db.tagDao(), db.itemDao(), db.itemTagDao()) } @After fun tearDown() { db.close() } private suspend fun bookTypeId(): Long { repo.ensureSeeded() return repo.itemTypes.first().first { it.name == "Book" }.id } @Test fun seedingIsIdempotent() = runTest { repo.ensureSeeded(); repo.ensureSeeded() assertEquals(listOf("Book", "CD", "DVD", "Blu-ray"), repo.itemTypes.first().map { it.name }) } @Test fun tagNamesAreUniqueIgnoringCase() = runTest { val a = repo.getOrCreateTag("Sci-Fi") val b = repo.getOrCreateTag(" sci-fi ") assertEquals(a.id, b.id) assertEquals(1, repo.tags.first().size) } @Test fun savingWithTagsLinksThemAndDeletingRemovesLinksOnly() = runTest { val id = repo.saveItemWithTagNames(Item(title = "Dune", itemTypeId = bookTypeId()), listOf("sci-fi", "classic")) val saved = repo.observeItem(id).first()!! assertEquals(setOf("sci-fi", "classic"), saved.tags.map { it.name }.toSet()) repo.deleteItem(saved.item) assertNull(repo.observeItem(id).first()) assertEquals(2, repo.tags.first().size) // the tags themselves remain } @Test fun duplicateCheckIgnoresCaseAndTheItemItself() = runTest { val type = bookTypeId() val id = repo.saveItemWithTagNames(Item(title = "Dune", creator = "Frank Herbert", itemTypeId = type), emptyList()) assertEquals(1, repo.findDuplicates("dune", "FRANK HERBERT", excludeId = 0).size) assertEquals(0, repo.findDuplicates("dune", "frank herbert", excludeId = id).size) } @Test fun importingTwiceDoesNotDuplicate() = runTest { val type = bookTypeId() repo.saveItemWithTagNames(Item(title = "Dune", itemTypeId = type, createdAt = 1000), listOf("sci-fi")) val json = repo.exportBackup() val result = repo.importBackup(json) assertEquals(ImportResult(added = 0, skipped = 1), result) assertEquals(1, repo.items.first().size) } }

The tests read like specifications of the app's own rules: seeding does not repeat, tag names are unique ignoring case, deleting an item removes its links but not the tags, a duplicate is detected but an item is not its own duplicate, and importing twice adds nothing. If you ever change the data layer, these are the five things that must still be true.

Layer 3: a view model

The list view model is tested by giving it a repository on an in-memory database, then driving it the way the screen does. Two coroutine-testing facts apply, both in the library's documentation: view model code that launches coroutines needs the main dispatcher replaced with a test one, and the debounce delay is virtual time, advanced by the test rather than waited for. Treat the next test as the least certain code in this chapter: tests that mix a real database (running on its own threads) with virtual time are the ones most likely to need adjusting.

@OptIn(ExperimentalCoroutinesApi::class) class ListViewModelTest { private lateinit var db: AppDatabase private lateinit var repo: CatalogueRepository @Before fun setUp() { Dispatchers.setMain(StandardTestDispatcher()) db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java).build() repo = CatalogueRepository(db, db.itemTypeDao(), db.tagDao(), db.itemDao(), db.itemTagDao()) } @After fun tearDown() { db.close() Dispatchers.resetMain() } @Test fun searchNarrowsTheList() = runTest { repo.ensureSeeded() val book = repo.itemTypes.first { it.isNotEmpty() }.first { it.name == "Book" }.id repo.saveItemWithTagNames(Item(title = "Dune", creator = "Frank Herbert", itemTypeId = book), emptyList()) repo.saveItemWithTagNames(Item(title = "Emma", creator = "Jane Austen", itemTypeId = book), emptyList()) val vm = ListViewModel(repo) vm.onQueryChange("dun") val state = vm.uiState.first { it.query == "dun" && it.items.size == 1 } assertEquals("Dune", state.items.single().item.title) assertEquals(2, state.totalCount) } }

Why first { ... } with a condition instead of a fixed wait? The state passes through several values on the way (loading, all items, then the filtered list); waiting for the one that matters makes the test independent of how long that takes. Add import kotlinx.coroutines.test.*, kotlinx.coroutines.Dispatchers and kotlinx.coroutines.ExperimentalCoroutinesApi.

Part 5: Where Next

The spec's "nice to have" list is the roadmap. For each, here is what actually changes, which tells you how big the job is:

FeatureWhat it needsTouches
Barcode scanningCameraX for the camera preview, ML Kit's barcode scanner to read the code, a camera permission requestA new screen; the form accepts a scanned value
Online lookup by ISBN or barcodeA network library (Retrofit or Ktor), an API such as Open Library or Google Books, the internet permission, parsing JSON, handling failures and no networkRepository gains a remote source; the form pre-fills from a result
ISBN, runtime, tracklist fieldsNew columns on the item (or type-specific tables), a Room migration from version 1 to 2, a backup format version = 2Data model, form labels, detail screen, backup
Cover artAn image loading library (Coil), storing or caching images, a bigger backup story (images are not in the JSON)Rows, detail, backup
Wish list, "lent to"A status field on Item or a new table, filters for itData model, list filters, form
Cloud syncFirebase (as in the web Personal Catalogue: Firebase course): authentication, conflict rules between devicesThe repository becomes the sync boundary; most screens unchanged

Notice how little the screens would change in several rows. That is the payoff of the architecture you built: the repository is the one seam, so new data sources slot in behind it. The most important lesson for the data-model rows is the migration: once the app is installed on a phone with real data, you cannot just edit an entity; you raise the database version and tell Room how to upgrade. In outline (the signature differs between Room versions, so check the migration page for yours):

// Version 1 -> 2: add an optional ISBN column. Existing rows get NULL. val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("ALTER TABLE item ADD COLUMN isbn TEXT") } } // ...and in the database builder: Room.databaseBuilder(context, AppDatabase::class.java, "catalogue.db") .addMigrations(MIGRATION_1_2) .build()

Because the backup file stores fields by name and ignores unknown keys, an old backup still imports into a newer app (the missing field takes its default), which is exactly why the file has a version number. A sensible next course would be a second Catalogue course adding barcode scanning with a lookup, and the data-model changes that go with it.

Compared with the iOS Course

Personal Catalogue: iOS (Swift & SwiftUI) builds the same ten chapters. Side by side, the whole project:

ChapterAndroid (this course)iOS (sister course)
1 SetupAndroid Studio, Gradle, emulatorXcode, Swift Package defaults, simulator
2 Data modelRoom entities, an explicit cross-reference classSwiftData @Model classes; the join is implicit
3 PersistenceDAOs, database class, repository, HiltModelContainer; no injection library
4-5 List, detailViewModel + StateFlow, LazyColumn, Navigation Compose@Query, List, NavigationStack
6-7 Form, tagsHoisted state in a view model, chips with FlowRowForm, bindings, a tag editor in SwiftUI
8 SearchSQL query with debounce and flatMapLatest.searchable and a #Predicate
9 PolishDialogs, theme checks, TalkBack, snackbarsAlerts, automatic dark mode, VoiceOver labels
10 Backup, testsStorage Access Framework, JUnit, in-memory RoomfileExporter/fileImporter, Swift Testing or XCTest

The honest summary: Android asks you to assemble more pieces yourself and gives you more control over where each one sits; iOS provides more of them already joined up. Neither is wrong, and having built both you can choose with your eyes open, which is the real goal of building one app twice.

What You Have Built

  • A native Android app in Kotlin and Jetpack Compose, with Room persistence, entirely offline.
  • A layered architecture (entities, DAOs, repository, view models, screens) in which each layer can be tested and replaced.
  • Features: add, edit and delete with per-type forms; a managed tag system; live search and filters; the "do I already own this?" flow; a duplicate warning; light and dark themes; accessibility basics; explicit error states; and a portable JSON backup.
  • Habits worth keeping: state hoisting, one source of truth, atomic transactions, never trusting an id you did not re-read, and testing the rules in order of cheapness.

Challenges

Exercise 1

Add the backup code and the Backup screen. Add six items, export, open the file in a text editor, then clear the app's storage and import. Record the message after the first import, then import the same file again and record that message. Edit one item's title inside the JSON file by hand and import that file: what happens, and why?

๐Ÿ“„ View solution
Exercise 2

Write and run the pure-function tests, then break the app on purpose: remove the "escape the backslash first" line from likePattern. Which test fails, and what does its message say? Put the line back. Then write one more test of your own for a rule from Chapters 2 to 9.

๐Ÿ“„ View solution
Exercise 3

Design (no need to build) the ISBN feature from the roadmap: list the data-model change, the Room migration, the new form field and label, the change to the backup format, and what an old backup file does when imported into the new app. Then say what a new backup does when imported into the old app.

๐Ÿ“„ View solution

Chapter 10 Quick Reference

  • Backup file: JSON with a version, items stored with type and tags by name, no database ids; ignoreUnknownKeys = true for forward compatibility
  • Import merges, skips items that match on title, creator, type and creation time, and is all-or-nothing in one withTransaction; decode the JSON before the transaction
  • Storage Access Framework: CreateDocument("application/json") to save, OpenDocument() to open; the user picks the file; no storage permission needed
  • rememberLauncherForActivityResult(contract) { uri -> ... }; uri is null if cancelled
  • File work on Dispatchers.IO: contentResolver.openOutputStream(uri, "wt") / openInputStream(uri)
  • Tests: pure functions (local, fast) → repository on an in-memory Room database (instrumented) → view model with a test main dispatcher
  • Changing an installed database means raising its version and adding a Migration
Not Yet Verified
Checked (two web searches on 2026-11-19): that the Storage Access Framework uses ACTION_CREATE_DOCUMENT and ACTION_OPEN_DOCUMENT, that the user selects the file and the app receives a URI permission for it; that rememberLauncherForActivityResult takes any ActivityResultContract and handles registering and unregistering; that Google's Room testing page recommends an in-memory database with runTest and closing it after each test, and describes newer setups I did not follow.
Not checked, from general knowledge: ContentResolver.openOutputStream(uri, "wt") and openInputStream in this combination; CreateDocument and OpenDocument constructor and launch signatures in your activity-compose version; kotlinx.serialization configuration options and behaviour of the generated serializers for the default values; that a thrown exception inside withTransaction rolls everything back; Icons.Filled.Settings; the migration class shape for your Room version; every test, including the ViewModel test's use of setMain with first { }; the JUnit and AndroidX test dependency setup; ML Kit and CameraX as the barcode route; and all code, none of which was compiled, and no test was run.
Sources for This Chapter
Search results (2026-11-19): Android Developers, DocumentsProvider; ManagedActivityResultLauncher API reference; Compose and other libraries; Test and debug your database (Room); Migrate your Room database; Lifecycle release notes. Only titles and short summaries in the search results were used.
Course Complete
That is the last chapter of Personal Catalogue: Android (Kotlin & Compose). If you also build Personal Catalogue: iOS (Swift & SwiftUI), compare your two finished apps against the table above, and note which parts felt natural on each platform: that judgement is the lasting product of this pair of courses.