Duplicates and Polish

Personal Catalogue: Android (Kotlin & Compose)

Course 1 ยท Chapter 9 ยท Warnings, Themes, Accessibility and Error States

The app now does everything the spec asks of it except the last item (backup, in Chapter 10). This chapter is the difference between an app that works and one you are happy to rely on. You will add a duplicate warning (the spec says "a warning, never a block"), check that the app looks right in light and dark themes, make it usable with a screen reader and large text, and replace the places where something can silently go wrong with proper loading, error and not-found states.

What was run, and what was not
Nothing was compiled or run (no Android Studio here), and nothing was tested with TalkBack or in dark mode: accessibility and appearance can only really be judged on a device, so treat this chapter's checks as a procedure for you to carry out. Three searches were made: the accessibility pages confirmed the 48dp touch-target rule, contentDescription = null for decorative icons and clearAndSetSemantics in Google's codelab; the Material 3 pages confirmed the theme pattern. Room's COLLATE NOCASE in a query and some semantics functions are from my memory.

Part 1: The Duplicate Warning

The spec's rule: when the user saves an item with the same title and creator (ignoring case) as one that exists, warn, but never block. A person can legitimately own two copies of a book, so the app's job is to ask, not to forbid. This is the reason Chapter 2 did not use a unique index (Exercise 2 there).

ApproachResultUsed here?
Unique index on title + creatorDatabase rejects the second copy; the user is blockedNo: contradicts the spec
Check in code, then askA query before saving; a dialog with "Save anyway"Yes
Check only at the end of typingEarly feedback, but more moving partsLeft as a later improvement

The query

Add to ItemDao. COLLATE NOCASE makes the comparison ignore case (for ASCII letters, the same limit as Chapter 8's search), and id != :excludeId stops an item being reported as a duplicate of itself when you edit it.

@Query( """ SELECT * FROM item WHERE title = :title COLLATE NOCASE AND creator = :creator COLLATE NOCASE AND id != :excludeId """ ) suspend fun findDuplicates(title: String, creator: String, excludeId: Long): List<Item>

In the repository, trim the values the same way the form does before saving, so "Dune " and "Dune" count as the same:

suspend fun findDuplicates(title: String, creator: String, excludeId: Long): List<Item> = itemDao.findDuplicates(title.trim(), creator.trim(), excludeId)

The form's save flow

Saving becomes a small decision tree: invalid, so show errors; duplicate found, so show the warning and wait; otherwise write. Two choices from Chapter 6 stay (the isSaving guard against double-taps, and carrying createdAt through an edit), and a third is new: every write is wrapped so a failure is reported instead of lost (Part 4 shows the other half). Add two fields to FormUiState:

val duplicateCount: Int = 0, // > 0 means: show the duplicate warning val saveFailed: Boolean = false, // true means: show the "could not save" message once

Replace save in FormViewModel with the following, and add the three small functions after it. (Import kotlinx.coroutines.CancellationException.)

fun save(onSaved: () -> Unit) { val s = _state.value if (s.isSaving) return if (!s.isValid) { _state.update { it.copy(showErrors = true) } return } _state.update { it.copy(isSaving = true) } viewModelScope.launch { guarded { val duplicates = repository.findDuplicates(s.title, s.creator, excludeId = itemId) if (duplicates.isNotEmpty()) { _state.update { it.copy(isSaving = false, duplicateCount = duplicates.size) } } else { write(s) onSaved() } } } } /** The user saw the warning and chose to go ahead. */ fun saveAnyway(onSaved: () -> Unit) { val s = _state.value if (s.isSaving) return _state.update { it.copy(isSaving = true, duplicateCount = 0) } viewModelScope.launch { guarded { write(s); onSaved() } } } fun dismissDuplicateWarning() = _state.update { it.copy(duplicateCount = 0) } fun errorShown() = _state.update { it.copy(saveFailed = false) } private suspend fun write(s: FormUiState) { repository.saveItemWithTagNames( Item( id = itemId, title = s.title.trim(), creator = s.creator.trim(), formatDetail = s.formatDetail.trim(), releaseYear = s.yearText.toIntOrNull(), notes = s.notes.trim(), createdAt = originalCreatedAt, itemTypeId = s.typeId!! ), tagNames = s.tagNames ) } /** Runs a save step; reports a failure instead of crashing or failing silently. */ private suspend fun guarded(block: suspend () -> Unit) { try { block() } catch (e: CancellationException) { throw e // never swallow cancellation } catch (e: Exception) { _state.update { it.copy(isSaving = false, saveFailed = true) } } }

Rethrowing CancellationException matters: coroutines use it to cancel work (for example when the user leaves the screen), and a blanket catch (e: Exception) that swallows it would break that. Catching the general Exception is acceptable here because the only thing we do is tell the user; a real app would also log it.

The dialog and the message in the form

Give FormContent three more parameters (onSaveAnyway, onDismissDuplicate, onErrorShown), pass them from FormScreen as { viewModel.saveAnyway(onDone) }, viewModel::dismissDuplicateWarning and viewModel::errorShown, and add the following. The failure message uses a snackbar: a brief message at the bottom of the screen that does not block anything.

// At the top of FormContent: val snackbarHostState = remember { SnackbarHostState() } LaunchedEffect(state.saveFailed) { if (state.saveFailed) { snackbarHostState.showSnackbar("Couldn't save. Please try again.") onErrorShown() } } // In the Scaffold( ... ) call, add: snackbarHost = { SnackbarHost(snackbarHostState) }, // After the Scaffold, still inside FormContent: if (state.duplicateCount > 0) { AlertDialog( onDismissRequest = onDismissDuplicate, title = { Text("You may already own this") }, text = { Text( "You already have ${state.duplicateCount} item${if (state.duplicateCount == 1) "" else "s"} " + "called \"${state.title.trim()}\" by the same creator. Save another copy anyway?" ) }, confirmButton = { TextButton(onClick = onSaveAnyway) { Text("Save anyway") } }, dismissButton = { TextButton(onClick = onDismissDuplicate) { Text("Go back") } } ) }

LaunchedEffect(state.saveFailed) runs its block when the key changes: it shows the snackbar once, then tells the view model the error was shown so it is not shown again after rotation. That "show once, then clear" step is the standard way to handle a one-off message that lives in state.

Part 2: Light and Dark Theme

The wizard generated ui/theme/Theme.kt in Chapter 1, and it already supports both themes. Google's Material 3 guide says to use isSystemInDarkTheme() to choose between a light and a dark scheme, and its codelab's theme function takes a darkTheme parameter that defaults to it. The generated file normally looks like this in outline (yours will differ in detail):

@Composable fun CatalogueTheme( darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = true, // colours from the wallpaper on Android 12+ content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme // built with darkColorScheme(...) else -> LightColorScheme // built with lightColorScheme(...) } MaterialTheme(colorScheme = colorScheme, typography = Typography, content = content) }

So you have very little to write; the work is to check. The rule that makes dark mode work is that screens use roles from the theme, such as MaterialTheme.colorScheme.primary and onSurface, and never a fixed colour. The code in this course has followed that rule, so the checks are:

  1. Search for hard-coded colours. Use Edit > Find > Find in Files for Color( and Color. in ui/ outside the theme folder. Any hit is a colour that will not change with the theme; replace it with a colorScheme role.
  2. Try both themes. On the emulator open Settings > Display > Dark theme and switch it while the app is open. Look at every screen: list, detail, form (with an error and with the duplicate dialog open) and the empty states.
  3. Preview both. Add a second @Preview with uiMode = Configuration.UI_MODE_NIGHT_YES next to each screen's preview, so you can compare them in the IDE.
  4. Dynamic colour and contrast. With dynamic colour on, the palette depends on the user's wallpaper, so you cannot check every combination; sticking to theme roles (text on its matching on... colour) is what keeps text readable.

The same parameter lets you force a theme regardless of the system setting, which is how an in-app "Light / Dark / System" choice is built; this course leaves that out because the spec only asks that both themes look right.

Part 3: Accessibility

Accessibility on Android mostly means three things: a screen reader (TalkBack) must be able to say what each element is and does; touch targets must be large enough; and text must survive being enlarged. Google's guidance supports each of these, and Compose does a lot for free: Material components such as Button and IconButton already enforce the 48dp minimum touch target. Your job is the gaps.

IssueWhere in this appFix
Icon with no descriptionBack, edit, delete, add, clear, remove-tag iconsAlready given a contentDescription in Chapters 4-8; check each one still reads naturally
Decorative iconThe search field's leading magnifiercontentDescription = null, as Chapter 8 wrote: Google's guidance says that tells the framework it has no action or state
A row read as many fragmentsList rows (title, creator, type, tags)Make the whole row one clickable unit with a clear action label
A clickable thing smaller than 48dpNothing now, but any future custom controlModifier.minimumInteractiveComponentSize()
Colour as the only signalForm errorsAlready text as well as red (supportingText), so no change
Large textRows and formsTest at the largest font size; keep maxLines and scrolling

The row fix is one change in Chapter 4's ItemRow. Giving the click an onClickLabel makes TalkBack announce "Open details" as the action instead of just "double-tap to activate". A clickable container already groups its children into one element for the screen reader; the label tells the user what the tap does.

Card( modifier = Modifier .fillMaxWidth() .clickable(onClickLabel = "Open details", onClick = onClick) ) { // ...unchanged... }

Google's accessibility codelab also shows clearAndSetSemantics, which replaces everything a TalkBack user would hear for an element with text you write yourself. It is powerful but easy to misuse: you take over responsibility for the whole description. Prefer the clickable label above, and reach for clearAndSetSemantics only when the automatic reading is genuinely wrong.

Now test. Turn on TalkBack (Settings > Accessibility > TalkBack), swipe through the list, detail and form screens, and listen: every control should announce what it is, and nothing should be read twice or not at all. Then set Settings > Display > Font size to the largest, and check nothing is cut off or unreachable. Google's "Accessibility Scanner" app (and the Compose accessibility testing guide) can flag missing labels and small targets automatically.

Part 4: Loading, Error and Not-Found States

A screen should always be in one of a few explicit states, never blank without explanation. Here is the audit for this app:

ScreenStateBefore this chapterAfter
ListLoadingA blank screen for a momentA progress indicator
ListEmpty, or no matchHandled (Chapters 4 and 8)No change
DetailLoading, not foundHandled (Chapter 5)No change
FormSave failsCrash, or nothingA snackbar, and the form stays as it was
DetailDelete failsCrash, or nothingExercise 3

Form errors are done (Part 1). For the list's loading state, change one line in ListContent's when from Chapter 8: state.isLoading -> Unit becomes

state.isLoading -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }

This is the smallest useful version. On a local database loading is nearly instant, so the indicator is rarely seen; it matters in the one case where it counts, the first launch after install while the database is being created and seeded.

A Limit: Hard-Coded Text
All the screen text in this course is written directly in the Kotlin code. A shipped app puts it in res/values/strings.xml and reads it with stringResource(R.string.x), which is what allows translation and lets accessibility tools and tests refer to strings by name. That is a mechanical change this course leaves out to keep the code readable; Android Development: Production & Publishing covers release preparation.
Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 9 the same four jobs appear. A confirmation dialog warns about duplicates; SwiftUI's semantic colours follow light and dark automatically; VoiceOver labels use .accessibilityLabel; and a failed save is shown with an alert. The difference is that on iOS much of this is automatic, whereas on Android you check more of it yourself.

Challenges

Exercise 1

Add the duplicate check, the new state, the save flow and the dialog. Test and record the result of: (a) adding "Dune" by "Frank Herbert" when "dune" by "frank herbert" exists; (b) editing that existing item and saving it unchanged; (c) adding "Dune" by "Someone Else"; (d) choosing "Save anyway" in case (a).

๐Ÿ“„ View solution
Exercise 2

Carry out the accessibility and theme checks on a device or emulator: dark theme, TalkBack and the largest font size. Write down at least three real findings (something unclear, cut off or awkward) and fix one of them.

๐Ÿ“„ View solution
Exercise 3

Chapter 5's DetailViewModel.delete has no error handling. Add it: report a failed delete to the user and keep them on the screen. Say where the state and the message should live.

๐Ÿ“„ View solution

Chapter 9 Quick Reference

  • Duplicate rule: same title and creator, case-insensitive: title = :title COLLATE NOCASE AND creator = :creator COLLATE NOCASE AND id != :excludeId; a warning, never a block
  • Save flow: invalid → show errors; duplicate → dialog with "Save anyway"; otherwise write; any failure → snackbar
  • Wrap writes in a function that rethrows CancellationException and reports other exceptions
  • One-off messages in state: show in LaunchedEffect(flag), then clear the flag
  • Theme: isSystemInDarkTheme(), lightColorScheme/darkColorScheme, dynamic colour on Android 12+; use theme roles, never fixed colours
  • Accessibility: meaningful contentDescription, null for decorative, onClickLabel on clickable rows, 48dp targets, test with TalkBack and the largest font
  • Every screen has explicit loading, empty, error and not-found states
Not Yet Verified
Checked (three web searches on 2026-11-19): that Google's guidance sets 48dp as the minimum touch target and that Material components such as Button and IconButton enforce it; that minimumInteractiveComponentSize exists for custom controls; that contentDescription = null marks decorative elements; that clearAndSetSemantics appears in Google's accessibility codelab; that isSystemInDarkTheme() chooses light or dark schemes and that a darkTheme parameter can override it; that dynamic colour needs Android 12 (API 31) and a fallback.
Not checked, from general knowledge: COLLATE NOCASE on query parameters in a Room @Query; clickable(onClickLabel = ...) and its effect on TalkBack; that a clickable Card merges its children's semantics; that FilterChip announces its selected state; SnackbarHost and LaunchedEffect usage details; the layout of your generated Theme.kt; the Accessibility Scanner app; and all code, none of which was compiled. No screen reader, dark-mode or large-font testing was done.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 10 is the last chapter: exporting the whole catalogue to a JSON file and importing it back with the Storage Access Framework, tests for the repository and the view models, and a roadmap (barcode scanning with CameraX and ML Kit), compared with the iOS course. The combined course PDF is built when it lands.