Android SharedPreferences Tutorial and Example

Filtering an Android List with Live Search

Adding search functionality to a list gives users a direct route to a relevant record. A contact picker, property catalogue, or event directory becomes cumbersome when every item must be scanned. A search field lets people narrow the collection by name, category, suburb, or another indexed value while the rest of the screen remains unchanged.

A dependable search field combines an EditText, a TextWatcher, and the adapter that controls the visible rows. The query can be applied to a local list immediately or sent to a database when the records are too large to hold in memory. In either case, retain the original dataset so clearing the field can restore every item without reloading the screen.

The details depend on the app architecture. RecyclerView with a ListAdapter is common for modern Android interfaces, while older projects may still use ListView and a traditional adapter. The same matching rules can serve both, but the methods used to publish filtered results differ. A small project can begin in memory and move filtering into Room or SQLite later without changing the search experience.

Good search also reflects Australian conventions. Records may contain Australian English spellings such as “organisation”, prices displayed as A$24.95 with GST included, and dates written in day-first order. An events catalogue can include summer dates in December and February, so matching should not assume Northern Hemisphere seasons. City names such as Sydney, Melbourne, and Brisbane should match regardless of letter case.

Approach Suitable collection Result handling Main consideration
In-memory filtering Small, already loaded list Copy matching items into a new list Fast to implement; grows with the dataset
Adapter filtering Moderate list held in a ViewModel Submit results to ListAdapter or notify a classic adapter Separates interface logic from source data
Database filtering Large Room or SQLite-backed catalogue Query rows and publish only matches Requires background work and careful state handling

Choose where the filtering belongs

For a list containing dozens or a few hundred records, in-memory filtering is usually enough. Keep a read-only allItems collection, derive a visibleItems list from the current query, and publish that list to the adapter. Matching several fields is straightforward: compare the title, subtitle, or category with contains and make the comparison case-insensitive.

With RecyclerView, ListAdapter and DiffUtil calculate the row changes after each query, avoiding a full redraw. A conventional adapter can use notifyDataSetChanged, although that gives the framework less information about what moved. Filter a copy rather than deleting records from the source, otherwise the next keystroke searches an already shortened collection and valid matches disappear.

Large catalogues need the filter to travel with the data request. Room can observe a query flow, while SQLite can return rows through a LIKE clause or a targeted search index. This filter the records guide explains how create, read, update, and delete operations affect the records available to search. Run database work away from the main thread and publish only the final results to the interface.

Connect the field to the adapter

Place an EditText above the list and give it a stable identifier in the layout. A TextWatcher receives each change, so the filter can refresh after typing, pasting, or clearing text. In Kotlin, the core of a local filter can remain compact:

searchEditText.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(text: Editable?) {
        val query = text?.toString().orEmpty().trim()
        val visible = allItems.filter { item ->
            item.name.contains(query, ignoreCase = true) ||
                item.subtitle.contains(query, ignoreCase = true)
        }
        adapter.submitList(visible)
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
})

The sample assumes that allItems contains the complete collection and that adapter is a ListAdapter. Trimming the query ignores accidental spaces, while keeping the original list immutable protects the source data. A blank query should submit the full collection, giving the clear button predictable behaviour.

If the source list changes, update allItems first and then reapply the latest query. This matters when records arrive from a network response, repository, or Room query. It also prevents a late refresh from replacing filtered rows with the unfiltered collection. For a plain ListView, assign the filtered list to the adapter and call notifyDataSetChanged; for ListAdapter, use submitList and let DiffUtil handle the update.

Give every query visible feedback

The layout should include an empty-state view for the period between loading and receiving results. After filtering, show it when the query has no matches, but use a different message when the source itself is empty. “No matching results” tells the user that the search worked, while “No items available” identifies a data or loading problem. A clear icon inside the field removes the query with one action.

Matching should cover the fields users are likely to remember. A contact may recall a suburb but not a surname, while a shopper may know only a product category. Split a multi-word query into trimmed terms and require each term to match at least one searchable field. Comparing normalised text handles extra spaces and capitalisation while retaining the original labels for display.

Do not discard the query when the activity rotates or the user opens another screen. Store it in the ViewModel, restore it through SavedStateHandle, and let the adapter rebuild the visible rows. Keep unrelated interface state, such as a selected event or current tab, separate from the search text. This separation makes navigation and configuration changes feel stable.

Keep filtering responsive at any size

Typing a long query can generate several updates in quick succession. For a modest local list, filtering on the main thread may be harmless, but a debounce of roughly 150 to 250 milliseconds reduces repeated work. The delay should remain imperceptible, and the clear action should apply immediately rather than waiting for another timer event.

Database-backed search belongs on an appropriate dispatcher. A Room repository can expose a Flow that combines the query with the source data, then map the results for the main thread. This keeps network, disk, and cursor work away from frame rendering. It also lets the screen show a progress indicator while a large query runs instead of freezing the list.

State lifetime needs careful handling. A ViewModel survives ordinary rotation, whereas SavedStateHandle preserves the query across process recreation when that durability is required. SharedPreferences can store a preferred or recent search for a later session, although it is not the best home for transient screen state. Release observers with the screen’s lifecycle so a closed activity cannot keep updating an old adapter.

Verify the Australian user journey

Test the behaviour with realistic Australian content rather than generic placeholders. Include names, suburbs, prices, and dates that match the records users will actually see.

Data and matching checks

  • Type syd and confirm that a Sydney record appears.
  • Search Melbourne in mixed case and verify the same result.
  • Match A$24.95 when prices are searchable.
  • Clear the field and confirm every source item returns.

Exercise the interface states that usually reveal defects.

Device and release checks

  • Rotate the device and confirm the query and results remain.
  • Open the screen after process recreation and restore the query.
  • Test a slow database response with a visible loading state.
  • Check accessibility labels, touch targets, and screen-reader order.

A release candidate is ready when each query produces the correct rows, the empty state explains the outcome, and the list remains responsive under realistic load. The same behaviour should hold for ListView, RecyclerView, and database-backed collections, with only the data-delivery layer changing between them.