Search and Filter

Personal Catalogue: Android (Kotlin & Compose)

Course 1 ยท Chapter 8 ยท Search, Tag Filter and "Do I Own This?"

This is the chapter that delivers the app's reason for existing. You are standing in a shop holding a paperback; you type three letters of its title; the phone tells you "You already have 1 match" or "Not in your catalogue", and in the second case one tap starts adding it with the title already filled in. Along the way you will move filtering from memory into the database, add a tag filter, and meet two Kotlin flow operators, debounce and flatMapLatest, that make live search behave.

What was run, and what was not
Nothing was compiled or run (no Android Studio here). Two searches were made for this chapter. The Kotlin side (debounce, flatMapLatest) is confirmed only by the official Flow reference and by forum discussions, which I treated as illustration rather than authority. The SQLite side (LIKE and ESCAPE) is confirmed from SQLite's own documentation. Room's handling of nullable query parameters and of the SQL inside @Query was not found in any source, so the DAO query is the likeliest place for a build error; Room checks the SQL when you build, so the message will name the problem.

Where the Filtering Happens

Chapter 4 filtered in memory: load every item, then discard the ones that do not match the selected type. That is fine for one condition, but search plus type plus tag would mean ever more Kotlin code that re-implements what a database does well. Now the filtering moves into one SQL query, and the view model just passes the user's choices to it.

ChoiceIn memory (Chapter 4)In the database (this chapter)
Cost as the collection growsReads every item on every changeReturns only the matches
Adding another filterMore filter { } linesOne more AND clause
Where the rules liveView modelDAO query (testable in Chapter 10)
Web catalogue equivalentFiltering a fetched array in JavaScriptItem.objects.filter(Q(title__icontains=q) | Q(creator__icontains=q))

Step 1: The Search Query

One DAO method takes three optional conditions: a text pattern, a type id and a tag id. A condition that is empty ('' or NULL) is switched off by the :param IS NULL OR ... idiom, so a single query serves every combination. Add it to ItemDao:

@Transaction @Query( """ SELECT * FROM item WHERE (:typeId IS NULL OR itemTypeId = :typeId) AND (:pattern = '' OR title LIKE :pattern ESCAPE '\' OR creator LIKE :pattern ESCAPE '\') AND (:tagId IS NULL OR id IN (SELECT itemId FROM item_tag WHERE tagId = :tagId)) ORDER BY createdAt DESC """ ) fun search(pattern: String, typeId: Long?, tagId: Long?): Flow<List<ItemWithDetails>> @Query("SELECT COUNT(*) FROM item") fun observeCount(): Flow<Int>

Read the three conditions as a sentence: the type matches (or no type was chosen), and the title or creator matches the pattern (or no pattern was typed), and the item carries the tag (or no tag was chosen). The tag test uses a subquery on the link table from Chapter 2, which is why that table has its own index on tagId. Each LIKE ends with ESCAPE '\', explained next. The count query lets the screen tell "your catalogue is empty" from "nothing matches" without loading everything.

The pattern, and why ESCAPE matters

SQLite's documentation says LIKE treats % as "any run of characters" and _ as "any one character", and that the ESCAPE clause names a single character that, placed before %, _ or itself, makes it literal. Without that, someone searching for the title "100% Pure" would have the % read as a wildcard. SQLite also documents that LIKE ignores case only for ASCII letters: "dune" matches "Dune", but "รฉ" does not match "ร‰". For a catalogue with a few accented titles that is a real, small limit, and Exercise 2's notes mention a fix. Put the pattern builder in data/Search.kt:

package com.example.catalogue.data /** Builds a LIKE pattern for "contains this text", or "" for no search at all. */ fun likePattern(raw: String): String { val q = raw.trim() if (q.isEmpty()) return "" val escaped = q .replace("\\", "\\\\") // the escape character itself first .replace("%", "\\%") .replace("_", "\\_") return "%$escaped%" }

Order matters: the escape character must be escaped first, or the backslashes added for % and _ would themselves be doubled. In the repository add:

val itemCount: Flow<Int> = itemDao.observeCount() fun search(query: String, typeId: Long?, tagId: Long?): Flow<List<ItemWithDetails>> = itemDao.search(likePattern(query), typeId, tagId)

Step 2: A Search That Waits for You to Stop Typing

A query on every keystroke is wasteful and makes the list flicker, so wait until the user pauses. debounce(250) does that: per the Flow reference, it drops a value if a newer one arrives within the timeout, and the latest value is always emitted. The second operator is flatMapLatest: it turns each set of filters into a database Flow and, when the filters change, cancels the old one and switches to the new. Without it, a slow earlier query could finish after a faster later one and overwrite the newer results.

Two details. The text box must show what is typed immediately, so the view model keeps the raw text in one flow and debounces a separate copy for searching. And chip taps should not be delayed, so only the text is debounced.

Step 3: State and ViewModel

ListUiState gains the query, the tag list and the selected tag; ListViewModel is rewritten around three input flows. This replaces the version from Chapter 4 (and its in-memory filtering) completely.

package com.example.catalogue.ui.list import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.catalogue.data.CatalogueRepository import com.example.catalogue.data.ItemType import com.example.catalogue.data.ItemWithDetails import com.example.catalogue.data.Tag import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch data class ListUiState( val isLoading: Boolean = true, val types: List<ItemType> = emptyList(), val tags: List<Tag> = emptyList(), val query: String = "", val selectedTypeId: Long? = null, val selectedTagId: Long? = null, val items: List<ItemWithDetails> = emptyList(), val totalCount: Int = 0 ) { val hasChipFilter: Boolean get() = selectedTypeId != null || selectedTagId != null val hasQuery: Boolean get() = query.isNotBlank() } private data class Controls(val query: String, val typeId: Long?, val tagId: Long?) @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) @HiltViewModel class ListViewModel @Inject constructor( private val repository: CatalogueRepository ) : ViewModel() { private val query = MutableStateFlow("") private val typeId = MutableStateFlow<Long?>(null) private val tagId = MutableStateFlow<Long?>(null) // What the controls show: immediate. private val controls = combine(query, typeId, tagId, ::Controls) // What the database is asked: the text waits for a pause, chips do not. private val results = combine(query.debounce(250), typeId, tagId, ::Controls) .distinctUntilChanged() .flatMapLatest { c -> repository.search(c.query, c.typeId, c.tagId) } val uiState: StateFlow<ListUiState> = combine( results, repository.itemTypes, repository.tags, repository.itemCount, controls ) { items, types, tags, count, c -> ListUiState( isLoading = false, types = types, tags = tags, query = c.query, selectedTypeId = c.typeId, selectedTagId = c.tagId, items = items, totalCount = count ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListUiState()) init { viewModelScope.launch { repository.ensureSeeded() } } fun onQueryChange(v: String) { query.value = v } fun onTypeSelected(id: Long?) { typeId.value = id } fun onTagSelected(id: Long) { tagId.update { current -> if (current == id) null else id } } // tap again to clear fun clearFilters() { query.value = "" typeId.value = null tagId.value = null } }

Note that distinctUntilChanged() stops a repeat query when the debounced text settles on a value the filters already hold. The @OptIn line acknowledges that debounce and flatMapLatest are marked as preview or experimental in the coroutines library; check which annotations your version asks for. Also, the removed "TEMPORARY" sample code from Chapter 6 is gone for good here.

Step 4: Passing the Title to the Form

The "Add" button in the not-found state must open the form with the searched text as the title. Give the route an optional starting title and use it in the form view model:

// Routes.kt @Serializable data class FormRoute(val itemId: Long = 0L, val initialTitle: String = "") // FormViewModel.kt: read the whole route once, and use it for the starting state private val route = savedStateHandle.toRoute<FormRoute>() private val itemId: Long = route.itemId private val _state = MutableStateFlow( FormUiState(isEdit = itemId != 0L, title = route.initialTitle) )

In the NavHost the list destination changes its add callback to take the title: onAddClick = { title -> navController.navigate(FormRoute(initialTitle = title)) }. The edit load in FormViewModel overwrites the title with the stored one, so initialTitle only affects a new item, as intended.

Step 5: The Screen

ListScreen now passes onQueryChange, onTagSelected and onClearFilters from the view model, and onAddClick becomes (String) -> Unit. Replace ListContent with the version below; TypeFilterRow and ItemRow from Chapter 4 stay as they are, and a second filter row is added for tags. Remember to update the preview or call sites for the new parameters.

@OptIn(ExperimentalMaterial3Api::class) @Composable fun ListContent( state: ListUiState, onQueryChange: (String) -> Unit, onTypeSelected: (Long?) -> Unit, onTagSelected: (Long) -> Unit, onClearFilters: () -> Unit, onAddClick: (String) -> Unit, onItemClick: (Long) -> Unit ) { Scaffold( topBar = { TopAppBar(title = { Text("My Catalogue") }) }, floatingActionButton = { FloatingActionButton(onClick = { onAddClick("") }) { Icon(Icons.Filled.Add, contentDescription = "Add item") } } ) { innerPadding -> Column(Modifier.padding(innerPadding)) { OutlinedTextField( value = state.query, onValueChange = onQueryChange, label = { Text("Search title or creator") }, leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) }, trailingIcon = { if (state.hasQuery) { IconButton(onClick = { onQueryChange("") }) { Icon(Icons.Filled.Close, contentDescription = "Clear search") } } }, singleLine = true, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp) ) TypeFilterRow(state, onTypeSelected) if (state.tags.isNotEmpty()) TagFilterRow(state, onTagSelected) when { state.isLoading -> Unit state.items.isEmpty() -> NoResults(state, onClearFilters, onAddClick) else -> { if (state.hasQuery) { Text( text = "You already have ${state.items.size} matching item${if (state.items.size == 1) "" else "s"}.", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) ) } LazyColumn( contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { items(state.items, key = { it.item.id }) { row -> ItemRow(row, onClick = { onItemClick(row.item.id) }) } } } } } } } @Composable private fun TagFilterRow(state: ListUiState, onTagSelected: (Long) -> Unit) { LazyRow( contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { items(state.tags, key = { it.id }) { tag -> FilterChip( selected = state.selectedTagId == tag.id, onClick = { onTagSelected(tag.id) }, label = { Text("#${tag.name}") } ) } } } /** The "do I already own this?" answer when nothing matches. */ @Composable private fun NoResults(state: ListUiState, onClearFilters: () -> Unit, onAddClick: (String) -> Unit) { Column( Modifier.fillMaxSize().padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { when { state.totalCount == 0 -> Text("Your catalogue is empty. Tap + to add your first item.") state.hasChipFilter -> { Text("Nothing matches the current filters.") TextButton(onClick = onClearFilters) { Text("Clear filters") } } else -> { Text("Not in your catalogue.", style = MaterialTheme.typography.titleMedium) Spacer(Modifier.height(12.dp)) Button(onClick = { onAddClick(state.query.trim()) }) { Text("Add \"${state.query.trim()}\"") } } } } }

The when in NoResults is the "do I own this?" logic, in order: no items at all; nothing under the chip filters (the answer is not "you don't own it", it is "not within these filters", so offer to clear them); otherwise the search text found nothing, which really does mean it is not in the catalogue, so offer to add it. That distinction is why the chip filters and the text query are tracked separately. Add Icons.Filled.Search and the other imports the IDE asks for.

Try It

Add a few items with different types and tags. Type part of a title: matching items appear after a short pause and the heading says how many you own. Type something you do not have: "Not in your catalogue" appears with an Add button; tap it and the form opens with the text as the title. Select a tag chip, then a type chip, and see them combine; tap the tag chip again to turn it off. Finally search for 100% and a_b to check that the escaping does not treat % and _ as wildcards.

Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 8, a .searchable modifier and a #Predicate in the @Query do the same job, and SwiftData rebuilds the query as the search text changes. The "do I own this?" answer and the add-with-title shortcut are the same design. The debounce and flatMapLatest plumbing mostly disappears there because SwiftUI re-runs the query itself.

Challenges

Exercise 1

Make all the changes and run the app. With at least six items (two of them tagged "sci-fi", one a CD), record what appears for each of: the search "dun"; the search "xyz"; the tag "sci-fi" alone; the tag "sci-fi" plus the type CD; and "xyz" with the tag "sci-fi" selected. Say which message each case shows and why they differ.

๐Ÿ“„ View solution
Exercise 2

Extend the search so it also matches the notes field. Say what you changed, whether the result is still sensible for a "do I own this?" check, and describe one way to make the search case-insensitive for accented letters (such as ร‰ and รฉ) despite the ASCII-only behaviour of LIKE.

๐Ÿ“„ View solution
Exercise 3

Explain, with a concrete example of timings, what could go wrong if the view model used map and collected each query's flow separately instead of flatMapLatest. Then say what the user would see if likePattern did not escape % and they searched for "100%".

๐Ÿ“„ View solution

Chapter 8 Quick Reference

  • One query, three optional conditions: (:x IS NULL OR col = :x); text: (:pattern = '' OR title LIKE :pattern ESCAPE '\' OR creator LIKE :pattern ESCAPE '\')
  • Tag filter: id IN (SELECT itemId FROM item_tag WHERE tagId = :tagId)
  • LIKE: % any run, _ any one; case-insensitive for ASCII only; escape \ first, then % and _
  • query.debounce(250) waits for a pause; flatMapLatest { repository.search(...) } cancels the previous query
  • Keep the displayed text and the searched (debounced) text as separate flows
  • Empty-result logic: no items → "empty catalogue"; chip filter active → "clear filters"; text only → "Not in your catalogue" + Add with the title
  • FormRoute(itemId, initialTitle) pre-fills the form for a new item
Not Yet Verified
Checked (two web searches on 2026-11-19): from the official Flow reference, that debounce drops values followed by newer ones within the timeout and always emits the latest, and that flatMapLatest maps each value to a flow and switches to the newest; from SQLite's documentation, that LIKE uses % and _, is case-insensitive for ASCII only, and that ESCAPE takes a single (ASCII) character that makes the next %, _ or itself literal.
Not checked, from general knowledge: that Room accepts nullable query parameters and the :param IS NULL OR idiom; that a backslash inside a Kotlin raw string reaches SQLite unchanged; that Room's compile-time SQL check accepts ESCAPE '\'; the exact opt-in annotations for debounce and flatMapLatest in your coroutines version; the combine overloads with a constructor reference; Icons.Filled.Search; and all code, none of which was compiled. The forum threads in the search results were informal and I did not treat them as sources.
Sources for This Chapter
Search results (2026-11-19): kotlinx.coroutines Flow reference; SQLite, SQL Language Expressions (LIKE and ESCAPE); SQLite User Forum: case insensitive like and accented letters (a user question, used only as an illustration of the accent limit). Only titles and short summaries in the search results were used.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 9 adds the duplicate warning when saving an item with the same title and creator, a light and dark theme check, accessibility labels, and proper error states.