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.

What was run, and what was not
Nothing was compiled or run (no Android Studio here). My search covered chips, 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

ProblemUnmanaged (free text)Managed (this chapter)
Case variants"Sci-Fi", "sci-fi", "SCI-FI" are three tagsOne tag; the stored spelling is reused
Stray spaces"sci-fi " and "sci-fi" differNames are trimmed and inner runs of spaces collapsed
Typos you've already fixed onceTyped again from scratch each timeSuggestions from existing tags as you type
Cancelled formStray empty tags left behindTags 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:

package com.example.catalogue.data private val whitespace = Regex("\\s+") /** Trims the name and turns any run of whitespace into a single space. */ fun normaliseTagName(raw: String): String = raw.trim().replace(whitespace, " ")

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.

/** Returns the existing tag with this name (any case), or creates it. */ suspend fun getOrCreateTag(rawName: String): Tag { val name = normaliseTagName(rawName) tagDao.findByName(name)?.let { return it } tagDao.insert(Tag(name = name)) // -1 if another insert won the race; either way the row now exists return tagDao.findByName(name)!! } // Replaces the old saveItem so both versions share the same writes. private suspend fun writeItem(item: Item, tagIds: Set<Long>): Long { val id = if (item.id == 0L) { itemDao.insert(item) } else { itemDao.update(item) item.id } itemTagDao.deleteForItem(id) itemTagDao.insertAll(tagIds.map { ItemTagCrossRef(itemId = id, tagId = it) }) return id } suspend fun saveItem(item: Item, tagIds: Set<Long>): Long = db.withTransaction { writeItem(item, tagIds) } /** Saves the item and links it to the named tags, creating any that do not exist yet. */ suspend fun saveItemWithTagNames(item: Item, tagNames: List<String>): Long = db.withTransaction { val ids = tagNames.filter { normaliseTagName(it).isNotEmpty() } .map { getOrCreateTag(it).id } .toSet() writeItem(item, ids) }

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:

// Add these properties to FormUiState: val allTags: List<Tag> = emptyList(), val tagNames: List<String> = emptyList(), // the tags chosen for this item val tagQuery: String = "", // what is typed in the tag box // ...and this computed property inside the class body: val suggestions: List<String> get() { val q = normaliseTagName(tagQuery) if (q.isEmpty()) return emptyList() return allTags.map { it.name } .filter { name -> name.contains(q, ignoreCase = true) && tagNames.none { it.equals(name, ignoreCase = true) } } .take(5) }

(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.

// 1. Delete: private var existingTagIds ... (no longer needed) // 2. In init { }, before the existing viewModelScope.launch, keep allTags up to date: viewModelScope.launch { repository.tags.collect { tags -> _state.update { it.copy(allTags = tags) } } } // ...and in the edit branch, replace the existingTagIds line with a tagNames entry: _state.update { it.copy( typeId = found.item.itemTypeId, title = found.item.title, creator = found.item.creator, formatDetail = found.item.formatDetail, yearText = found.item.releaseYear?.toString().orEmpty(), notes = found.item.notes, tagNames = found.tags.map { tag -> tag.name }.sorted() ) } // 3. New functions: fun onTagQueryChange(v: String) = _state.update { it.copy(tagQuery = v) } fun addTag(raw: String) { val name = normaliseTagName(raw) if (name.isEmpty()) return _state.update { s -> // Reuse the stored spelling if the tag already exists in another case. val canonical = s.allTags.firstOrNull { it.name.equals(name, ignoreCase = true) }?.name ?: name if (s.tagNames.any { it.equals(canonical, ignoreCase = true) }) { s.copy(tagQuery = "") } else { s.copy(tagNames = s.tagNames + canonical, tagQuery = "") } } } fun removeTag(name: String) = _state.update { s -> s.copy(tagNames = s.tagNames - name) } // 4. In save(), replace the repository.saveItem(...) call: 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 )

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.

package com.example.catalogue.ui.form import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp @OptIn(ExperimentalLayoutApi::class) @Composable fun TagEditor( selected: List<String>, query: String, suggestions: List<String>, onQueryChange: (String) -> Unit, onAdd: (String) -> Unit, onRemove: (String) -> Unit ) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedTextField( value = query, onValueChange = onQueryChange, label = { Text("Add a tag") }, singleLine = true, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions(onDone = { onAdd(query) }), trailingIcon = { TextButton(onClick = { onAdd(query) }, enabled = query.isNotBlank()) { Text("Add") } }, modifier = Modifier.fillMaxWidth() ) if (suggestions.isNotEmpty()) { Text("Existing tags", style = MaterialTheme.typography.labelMedium) FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { suggestions.forEach { name -> SuggestionChip(onClick = { onAdd(name) }, label = { Text(name) }) } } } if (selected.isNotEmpty()) { FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { selected.forEach { name -> InputChip( selected = true, onClick = { onRemove(name) }, label = { Text(name) }, trailingIcon = { Icon(Icons.Filled.Close, contentDescription = "Remove tag $name") } ) } } } } }

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:

TagEditor( selected = state.tagNames, query = state.tagQuery, suggestions = state.suggestions, onQueryChange = onTagQueryChange, onAdd = onAddTag, onRemove = onRemoveTag )

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.

Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 7, tags are a @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

Exercise 1

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 solution
Exercise 2

Tags 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.

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution

Chapter 7 Quick Reference

  • Managed tags: suggestions (ease), normaliseTagName (cleaning), unique NOCASE index (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 private writeItem shared with saveItem (no nested transactions)
  • Reuse the stored spelling: a typed "SCI-FI" becomes the existing "sci-fi"
  • FlowRow wraps chips; InputChip shows a removable chip; SuggestionChip offers an existing tag
  • KeyboardOptions(imeAction = ImeAction.Done) + KeyboardActions(onDone = { ... }) for the Done key
Not Yet Verified
Checked (one web search on 2026-11-19): that 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.
Sources for This Chapter
Search results (2026-11-19): InputChip API reference; FlowRow API reference; KeyboardActions API reference; Configure text fields; Compose Foundation release notes. Only titles and short summaries in the search results were used.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 8 adds search by title or creator, filtering by tag on the list screen, and the "do I already own this?" flow: a quick-check search designed for use in a shop.