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.
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).
| Approach | Result | Used here? |
|---|---|---|
| Unique index on title + creator | Database rejects the second copy; the user is blocked | No: contradicts the spec |
| Check in code, then ask | A query before saving; a dialog with "Save anyway" | Yes |
| Check only at the end of typing | Early feedback, but more moving parts | Left 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.
In the repository, trim the values the same way the form does before saving, so "Dune " and "Dune" count as the same:
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:
Replace save in FormViewModel with the following, and add the three small functions after it. (Import kotlinx.coroutines.CancellationException.)
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.
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):
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:
- Search for hard-coded colours. Use Edit > Find > Find in Files for
Color(andColor.inui/outside the theme folder. Any hit is a colour that will not change with the theme; replace it with acolorSchemerole. - 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.
- Preview both. Add a second
@PreviewwithuiMode = Configuration.UI_MODE_NIGHT_YESnext to each screen's preview, so you can compare them in the IDE. - 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.
| Issue | Where in this app | Fix |
|---|---|---|
| Icon with no description | Back, edit, delete, add, clear, remove-tag icons | Already given a contentDescription in Chapters 4-8; check each one still reads naturally |
| Decorative icon | The search field's leading magnifier | contentDescription = null, as Chapter 8 wrote: Google's guidance says that tells the framework it has no action or state |
| A row read as many fragments | List rows (title, creator, type, tags) | Make the whole row one clickable unit with a clear action label |
| A clickable thing smaller than 48dp | Nothing now, but any future custom control | Modifier.minimumInteractiveComponentSize() |
| Colour as the only signal | Form errors | Already text as well as red (supportingText), so no change |
| Large text | Rows and forms | Test 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.
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:
| Screen | State | Before this chapter | After |
|---|---|---|---|
| List | Loading | A blank screen for a moment | A progress indicator |
| List | Empty, or no match | Handled (Chapters 4 and 8) | No change |
| Detail | Loading, not found | Handled (Chapter 5) | No change |
| Form | Save fails | Crash, or nothing | A snackbar, and the form stays as it was |
| Detail | Delete fails | Crash, or nothing | Exercise 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
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.
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.
.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
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 solutionCarry 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 solutionChapter 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.
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
CancellationExceptionand 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,nullfor decorative,onClickLabelon clickable rows, 48dp targets, test with TalkBack and the largest font - Every screen has explicit loading, empty, error and not-found states
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.