Android SharedPreferences Tutorial and Example

Creating a Search Interface with Auto-Suggest

A search interface with auto-suggest should narrow results as the user types instead of waiting for a full query. A shopper looking for a Woolworths near Parramatta, for example, should be able to enter “Parr” and see matching Australian supermarket locations quickly.

Android offers an inline AutoCompleteTextView for a persistent field and a SearchView for a toolbar. Both can display suggestions, although they use different adapters and interaction patterns. The examples here use the inline control because its filtering flow is easy to inspect.

The sample is a Kotlin venue finder that grows from a local list to indexed SQLite search. It also covers debounced queries, selection, loading states, and accessible behaviour on real devices.

Choosing the right search control

Use an inline field when searching is the main purpose of the screen, such as finding a store, clinic, or event venue. Place a visible label above it and leave enough room beneath the field for the suggestion dropdown to expand without covering other controls.

A SearchView works better when search is one action among several. It can sit inside an app toolbar, expand across the available width, and retain familiar platform search icons and keyboard behaviour. Its suggestions usually come from a cursor adapter or a custom filtering model.

For this project, AutoCompleteTextView keeps the implementation visible. Set android:completionThreshold="1" to allow the dropdown to appear after the first character, and use android:imeOptions="actionSearch" to provide a clear keyboard action. Network requests should still wait briefly between keystrokes.

Preparing searchable local data

Represent every suggestion with a stable identifier and the text shown to the user. The identifier should travel to the destination screen because separate locations can have similar names.

data class VenueSuggestion(
    val id: Long,
    val name: String,
    val suburb: String,
    val state: String,
    val category: String
) {
    override fun toString() = "$name, $suburb"
}

A local ArrayList is suitable for a small demonstration or a short list of Australian venues. The sample can include Woolworths and Coles stores around Sydney, Melbourne, and Brisbane, with each suburb recorded in its own state. This keeps matching predictable until the catalogue becomes too large for in-memory filtering.

SQLite full-text search becomes useful as the catalogue grows. An FTS index over the name, suburb, and category supports fast prefix matching, while a parameterised query keeps the response focused:

SELECT venue_id, name, suburb, state, category
FROM venue_search
WHERE venue_search MATCH ?
ORDER BY rank
LIMIT 8;

Treat user input as search terms rather than SQL syntax, and escape any FTS operator characters before constructing the match expression.

Wiring suggestions to the adapter

The dropdown needs a text field, a row layout, and an adapter that connects them. Android’s simple dropdown layout works for a prototype, while a custom layout can later show the venue name in bold with its suburb or category underneath.

<AutoCompleteTextView
    android:id="@+id/search_input"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:imeOptions="actionSearch"
    android:completionThreshold="1" />

ArrayAdapter already provides prefix filtering, which makes it useful for a local list. Its toString() value controls both matching and display, so the model should produce a predictable format instead of exposing a generated data-class string.

class VenueAdapter(context: Context) :
    ArrayAdapter<VenueSuggestion>(
        context,
        android.R.layout.simple_dropdown_item_1line
    ) {
    fun replaceAll(items: List<VenueSuggestion>) {
        clear()
        addAll(items)
        notifyDataSetChanged()
    }
}

When SQLite supplies the results, call replaceAll on the main thread after the query finishes. The adapter’s built-in filter can narrow those returned matches, but it should not replace the indexed query for a large catalogue.

Debouncing queries without blocking the interface

A text watcher runs whenever the user types, deletes, pastes, or corrects a character. Local filtering can happen immediately, but SQLite or remote searches should pause briefly so that “parramatta” does not trigger separate requests for every prefix.

Use a coroutine job to cancel the previous request and start a delayed replacement. Checking the current query before updating the adapter prevents an older response from replacing newer results.

private var searchJob: Job? = null

searchInput.doAfterTextChanged { editable ->
    val query = editable?.toString().orEmpty()
    searchJob?.cancel()
    searchJob = lifecycleScope.launch {
        delay(250)
        val matches = withContext(Dispatchers.IO) {
            repository.search(query)
        }
        if (query == searchInput.text.toString()) {
            adapter.replaceAll(matches)
        }
    }
}

Use viewLifecycleOwner.lifecycleScope when this code belongs to a fragment, and cancel the job when the view disappears. A 250-millisecond delay suits most catalogue searches, although a remote API may need a longer pause. An empty query can return popular destinations, recent searches, or no results depending on the application.

Turning a suggestion into a result

Handle the dropdown’s item click by retrieving the selected venue’s stable identifier. Pass that identifier through an Intent extra and let the destination screen load the full record. This is more reliable than passing formatted text that might contain commas or ambiguous place names.

The keyboard’s search action should follow the same selection path as tapping a suggestion. Hide the keyboard after a valid choice, announce the selected place to accessibility services, and retain the query if the user needs to return and refine it. Clear outdated results when the underlying catalogue changes.

For a flow that combines place search with availability dates, the date picker examples show a practical pattern for adding a date-selection dialog. Australian interfaces commonly use day-first ordering, so display a value such as 08/03/2026 clearly and avoid relying on month names alone.

Handling empty, loading, and failure states

Show a concise empty message beneath the field, such as “No matching places found,” while retaining the typed text so it can be corrected. A small progress indicator can appear beside the field during a slow lookup without disabling the keyboard. Announce result counts through an accessibility live region so updates are not visual-only.

Mobile coverage can vary for commuters crossing Sydney, Melbourne, or Brisbane, particularly around underground stations and tunnels. Cache recent venue records, display the last known results after a connection drops, and label them as cached. If result cards include prices, format them in Australian dollars and apply any currency conversion only once.

Developers who edit Kotlin or XML in Emacs can use the Magik macro guidance to speed up repetitive changes to adapters and resources. Normal unit tests and Android UI tests should remain the safety net for those edits.

Give the search field a meaningful accessibility label, a sufficient touch target, and text that remains legible at large display sizes. Test the dropdown with TalkBack, ensure focus order follows the field and suggestions, and avoid using colour as the only sign that a result is selected.

Comparing the main implementation choices

A small local list needs little more than an adapter, while a growing catalogue benefits from indexed queries and explicit loading states. The main differences are where filtering occurs and how much interface work each control requires.

Approach Best fit Suggestion source Main trade-off
AutoCompleteTextView with ArrayAdapter Small local catalogue In-memory list Minimal setup, limited scaling
AutoCompleteTextView with SQLite FTS Growing offline catalogue Indexed database Requires queries and asynchronous updates
SearchView with suggestions Toolbar-driven application Cursor or filtered data Fits app-bar patterns but adds setup
Filtered RecyclerView Rich results with images and actions ViewModel-backed flow Strong layout control, greatest code cost

For most beginner Android projects, the local-adapter approach provides the quickest dependable result. The SQLite option preserves the same visible interaction while scaling cleanly to many Australian locations.