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.
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 item | Built in |
|---|---|
| 1. Add, edit, delete, labels per type | Chapters 5 and 6 |
| 2. List, newest first, type filter | Chapters 4 and 8 |
| 3. Detail screen | Chapter 5 |
| 4. Managed tags | Chapters 2, 3 and 7 |
| 5. Search and tag filter | Chapter 8 |
| 6. Duplicate warning | Chapter 9 |
| 7. Local storage, offline | Chapters 2 and 3 |
| 8. Light and dark theme, empty states, accessibility | Chapters 4, 8 and 9 |
| 9. Backup: export and import JSON | This 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.
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:
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.
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).
| Step | Export | Import |
|---|---|---|
| Contract | ActivityResultContracts.CreateDocument("application/json") | ActivityResultContracts.OpenDocument() |
| Launch | launcher.launch("catalogue-backup.json") (suggested name) | launcher.launch(arrayOf("application/json", ...)) (accepted types) |
| Result | A Uri (or null if cancelled) | A Uri (or null if cancelled) |
| Your code | Open an output stream on the Uri and write the JSON | Open an input stream on the Uri, read the text, import it |
| Web equivalent | A "Download backup" link | A 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.
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.
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:
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:
| Layer | Tests | Where it runs | Folder |
|---|---|---|---|
| Pure functions | likePattern, normaliseTagName, JSON round trip | Your computer, in milliseconds (a local test) | app/src/test/... |
| Repository on a real database | Saving with tags, cascades, duplicates, import | An emulator or device (an instrumented test), with an in-memory database | app/src/androidTest/... |
| View model | Search state, filters | Same as the repository, because it uses the real repository | app/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
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.
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.
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:
| Feature | What it needs | Touches |
|---|---|---|
| Barcode scanning | CameraX for the camera preview, ML Kit's barcode scanner to read the code, a camera permission request | A new screen; the form accepts a scanned value |
| Online lookup by ISBN or barcode | A network library (Retrofit or Ktor), an API such as Open Library or Google Books, the internet permission, parsing JSON, handling failures and no network | Repository gains a remote source; the form pre-fills from a result |
| ISBN, runtime, tracklist fields | New columns on the item (or type-specific tables), a Room migration from version 1 to 2, a backup format version = 2 | Data model, form labels, detail screen, backup |
| Cover art | An 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 it | Data model, list filters, form |
| Cloud sync | Firebase (as in the web Personal Catalogue: Firebase course): authentication, conflict rules between devices | The 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):
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:
| Chapter | Android (this course) | iOS (sister course) |
|---|---|---|
| 1 Setup | Android Studio, Gradle, emulator | Xcode, Swift Package defaults, simulator |
| 2 Data model | Room entities, an explicit cross-reference class | SwiftData @Model classes; the join is implicit |
| 3 Persistence | DAOs, database class, repository, Hilt | ModelContainer; no injection library |
| 4-5 List, detail | ViewModel + StateFlow, LazyColumn, Navigation Compose | @Query, List, NavigationStack |
| 6-7 Form, tags | Hoisted state in a view model, chips with FlowRow | Form, bindings, a tag editor in SwiftUI |
| 8 Search | SQL query with debounce and flatMapLatest | .searchable and a #Predicate |
| 9 Polish | Dialogs, theme checks, TalkBack, snackbars | Alerts, automatic dark mode, VoiceOver labels |
| 10 Backup, tests | Storage Access Framework, JUnit, in-memory Room | fileExporter/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
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 solutionWrite 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.
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 solutionChapter 10 Quick Reference
- Backup file: JSON with a
version, items stored with type and tags by name, no database ids;ignoreUnknownKeys = truefor 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 -> ... };uriisnullif 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
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.