Tags
Personal Catalogue: Android (Kotlin & Compose)
Course 1 ยท Chapter 7 ยท Managed Tags and Many-to-Many Writes
Tags are what make a catalogue searchable by meaning: "sci-fi", "birthday present", "lent out". Chapter 2 gave them a table and a case-insensitive unique name, and Chapter 6's form carries an item's existing tags through an edit without letting you change them. This chapter adds the tag controls to the form: type a tag and pick from suggestions of tags you already have, see the chosen tags as removable chips, and save everything in one go. The aim is the spec's rule: a managed list, so "Web Development" and "web development" can never become two tags.
FlowRow and the keyboard's Done action separately, and found no example combining them, so the tag
editor is my own assembly. The sources disagree about which opt-in annotation FlowRow needs (ExperimentalLayoutApi in the API reference, an earlier alpha
said ExperimentalFoundationApi), so if the IDE objects to the one used here, swap it.
What "Managed" Means
| Problem | Unmanaged (free text) | Managed (this chapter) |
|---|---|---|
| Case variants | "Sci-Fi", "sci-fi", "SCI-FI" are three tags | One tag; the stored spelling is reused |
| Stray spaces | "sci-fi " and "sci-fi" differ | Names are trimmed and inner runs of spaces collapsed |
| Typos you've already fixed once | Typed again from scratch each time | Suggestions from existing tags as you type |
| Cancelled form | Stray empty tags left behind | Tags are only created when the item is saved |
Three layers cooperate, and each catches what the one before misses: the suggestions make the right choice easy, the normalising function cleans what the user types, and the database's case-insensitive unique index (Chapter 2) is the final guarantee. Do not rely on the first two alone: a bug in them, or the JSON import in Chapter 10, would otherwise break the rule.
Step 1: Normalise Names and Fix getOrCreateTag
Chapter 3 ended with a warning: getOrCreateTag returned a tag with the wrong id if the insert was ignored. Fix that now, and add a function that cleans a name. Put the function in
data/TagNames.kt:
In CatalogueRepository replace getOrCreateTag and add a second save function. The new one resolves tag names into ids and writes the item in one transaction, so
a failure part-way leaves no half-saved item and no stray tags. To avoid nesting one withTransaction inside another, both public functions share a private helper that does the writes and
leaves the transaction to the caller.
The !! in getOrCreateTag is justified because, after an insert that either succeeded or was ignored because the name already exists, a row with that name must be present; if it is not,
something is badly wrong and a crash is more honest than a silent wrong id. Note that the unique index is case-insensitive, so findByName("SCI-FI") finds the stored "sci-fi" (Chapter 3 explained why).
Step 2: Tag State in the Form
The form keeps the chosen tags as a list of names, not ids. A brand-new tag has no id yet (and should not get one if the user cancels), so names are the one thing every tag, existing or new, has.
Four small additions to FormUiState:
(Import com.example.catalogue.data.Tag and normaliseTagName.) Suggestions are everything existing whose name contains what is typed, not already chosen, capped at five so the
screen does not fill up. An exact "starts with" match is a common alternative; "contains" is more forgiving of the user's memory.
Step 3: Tag Logic in the ViewModel
Four changes to FormViewModel: load the list of all tags, load an edited item's tag names instead of its ids, handle adding and removing, and save through the new repository function.
The key line is canonical. If the user types "SCI-FI" and "sci-fi" already exists, the chip shows "sci-fi", the stored spelling, so the screen never displays a name that will not be saved.
One small decision: any text left in the tag box at the moment of Save is not added; the Add button, the keyboard's Done key or a tapped suggestion adds a tag, and Exercise 3 asks you to consider
changing that.
Step 4: The Tag Editor
One composable, in ui/form/TagEditor.kt, holds the whole control. Like everything in this course it is stateless: it is given the chosen tags, the query and the suggestions, and reports what
the user does.
FlowRow lays chips out left to right and wraps onto new lines, which is what a variable-length set of tags needs (a LazyRow would scroll sideways and hide most of them). The
ImeAction.Done option puts a Done key on the keyboard and onDone runs when it is pressed. Each chosen tag's close icon has a contentDescription naming the tag, so a
screen reader says "Remove tag sci-fi" rather than just "Close".
Step 5: Put It in the Form
Add three parameters to FormContent (onTagQueryChange, onAddTag, onRemoveTag), pass them from FormScreen as
viewModel::onTagQueryChange, viewModel::addTag and viewModel::removeTag, and insert this block in the column between the Year field and the Notes field:
Run it. Add an item with tags "sci-fi" and "classic". Add a second item and type "sci" in the tag box: "sci-fi" should appear as a suggestion. Type "SCI-FI" in full and press Done: the chip should read "sci-fi". Open the first item for editing: its two tags are there, and removing one and saving changes the item's tags without disturbing its creation date.
@Model related to items, and SwiftData maintains the join for you. The tag editor is the same idea in SwiftUI: a text
field, a filtered list of suggestions and a wrapping row of chips. The uniqueness rule needs the same defence in depth: normalise the name, reuse an existing tag, and check again at save time.
Challenges
Make all five changes and run the app. Test and record the result of each case: (a) add "sci-fi" to one item; (b) on another item type "SCI-FI" and press Done; (c) type " retro games " with extra spaces; (d) add the same tag twice to one item; (e) start adding a new tag, then press Cancel and check no new tag appears in the suggestions of the next form.
๐ View solutionTags that no item uses are clutter. Write a DAO query that deletes them, a repository function that calls it, and decide where in the app it should be called. Explain why
calling it inside the same transaction as saveItemWithTagNames is both convenient and slightly risky.
A user types a tag, forgets to press Add, and presses Save: the tag is lost. Decide how save() should treat leftover text in tagQuery, implement it, and say whether
your solution belongs in the view model or the composable, and why.
Chapter 7 Quick Reference
- Managed tags: suggestions (ease),
normaliseTagName(cleaning), uniqueNOCASEindex (guarantee) getOrCreateTag: find by name, else insert, then re-read; never trust the id from an ignored insert- Form keeps chosen tags as names; tags are created only on Save, inside
db.withTransaction saveItemWithTagNames(item, names)resolves names to ids and calls a privatewriteItemshared withsaveItem(no nested transactions)- Reuse the stored spelling: a typed "SCI-FI" becomes the existing "sci-fi"
FlowRowwraps chips;InputChipshows a removable chip;SuggestionChipoffers an existing tagKeyboardOptions(imeAction = ImeAction.Done)+KeyboardActions(onDone = { ... })for the Done key
InputChip exists in Material 3 with a documented wrapping example using FlowRow; that FlowRow is marked
experimental (with the sources disagreeing on the annotation); that KeyboardActions.onDone runs when the Done action is triggered; and that keyboard actions attach to text fields, not chips.Not checked, from general knowledge: the exact parameters of
InputChip and SuggestionChip in your Material 3 version; ImeAction.Done import paths;
that Icons.Filled.Close is in the core icon set; a TextButton as trailingIcon; that Room's withTransaction calls from inside the transaction block
(getOrCreateTag uses DAO calls, not a nested withTransaction) behave as expected; that the NOCASE collation applies in findByName; and all code, none of which was compiled.