Android SharedPreferences Tutorial and Example

Build a filter and sort system for Android lists

Filtering and sorting solve different problems in an Android list. Filtering reduces the visible records to those matching a query or selected options, while sorting rearranges the remaining records by a defined rule. A reliable implementation keeps those stages separate so a new search never destroys the original dataset.

RecyclerView with ListAdapter is a practical Kotlin foundation because it supports efficient row updates and animated changes. The same design can be adapted to a classic ListView, but a modern app should define one immutable source list, derive a filtered snapshot, and submit that snapshot for display.

Choose a filtering approach

Approach Best fit Main benefit Main limitation
RecyclerView and ListAdapter Most new screens Incremental updates Slight setup cost
ListView with Filterable Older Android projects Built-in filtering hook Dated update model
In-memory predicates Small local collections Simple and fast Recalculates items
Server-side queries Large or changing datasets Scales beyond device memory Requires backend support

For a new Android application, choose RecyclerView and ListAdapter. Use in-memory filtering when the user has only a few hundred records, and move matching and ordering to the server when the catalogue is large or changes frequently. A backend query should return an ordered result set because the phone should not download records that the user cannot see.

Keep the active controls outside the adapter. The adapter renders a supplied list, while a controller or ViewModel owns the query, selected filters, and sort mode. This separation makes the behaviour easier to test and allows the same records to feed a search screen, picker, and details screen.

Model the data safely

Start with an immutable item model. Hold every record in an immutable allItems collection and maintain a separate visibleItems snapshot. Never remove rejected records from the source, since clearing a filter must instantly restore the complete list without another network request.

data class Customer(
    val id: Long,
    val name: String,
    val suburb: String,
    val totalSpend: Double
)

class CustomerFilter(private val allItems: List<Customer>) {
    fun apply(query: String): List<Customer> {
        val needle = query.trim()
        return if (needle.isEmpty()) {
            allItems
        } else {
            allItems.filter {
                it.name.contains(needle, ignoreCase = true) ||
                    it.suburb.contains(needle, ignoreCase = true)
            }
        }
    }
}

Use IDs as stable keys for RecyclerView. Names can repeat, and records can be renamed after an order is calculated; an ID identifies the same entity without forcing the entire list to lose its scroll position. Snapshot-based filtering also prevents a text listener from observing a list that is being changed halfway through a comparison.

Connect search to the adapter

Connect an EditText or SearchView to a text listener and pass the current query into the filter. Avoid expensive work on every keystroke by debouncing short delays and cancelling obsolete jobs. For a list of people, an alphabetical side index offers quick jumps to surnames, although it complements rather than replaces free-text matching.

searchBox.doAfterTextChanged { text ->
    searchJob?.cancel()
    searchJob = viewLifecycleOwner.lifecycleScope.launch {
        delay(250)
        val visible = customerFilter.apply(text?.toString().orEmpty())
        customerAdapter.submitList(visible)
    }
}

Normalise whitespace and decide whether matching is exact, prefix-based, or contains-based. A short query often produces too many matches when every character can appear anywhere, so a practical rule is to accept prefix matches for names and add a fallback contains match only for the remaining records. Keep the query in the ViewModel when the screen rotates, otherwise the adapter can briefly display an outdated result.

Give users immediate feedback when no records match. State that the query or filters are active, provide a clear action within the screen, and avoid changing the sort mode automatically. The visible count can help, but it should be announced accessibly rather than relying on colour alone.

Define deterministic sorting rules

Sorting should be deterministic. Define a comparator for each mode, such as name, newest purchase, or highest spend, and always apply a final comparison by unique ID. The tie-breaker prevents rows from moving unpredictably when two customers have the same name or exactly the same total.

val nameOrder = compareBy<Customer>(
    { it.name.lowercase(Locale.getDefault()) },
    { it.id }
)

val spendOrder = compareByDescending<Customer> { it.totalSpend }
    .thenBy { it.id }

For Australian names, use a locale-aware Collator with Locale("en", "AU") instead of relying only on lowercase strings. It handles accented characters more naturally and keeps the expected ordering for places such as Adelaide, Brisbane, Canberra, Melbourne, Perth, and Sydney. Convert currency only for display; sorting decimal amounts directly avoids rounding errors, and label the result in Australian dollars when relevant.

Keep list updates responsive

Submit a new snapshot only after filtering and sorting have finished. ListAdapter calculates differences with DiffUtil and updates visible rows without recreating the whole view hierarchy. Give each item a stable ID and keep the comparator pure, because any changing value inside a sort key can produce incorrect animations or inconsistent ordering.

private val customerDiff = object : DiffUtil.ItemCallback<Customer>() {
    override fun areItemsTheSame(oldItem: Customer, newItem: Customer) =
        oldItem.id == newItem.id

    override fun areContentsTheSame(oldItem: Customer, newItem: Customer) =
        oldItem == newItem
}

Filtering a few hundred local items is usually fast enough on the main thread, but larger collections should run matching and sorting on Dispatchers.Default. Return to the main thread before calling submitList, and cancel or ignore stale work when the query changes. A ViewModel can retain the last query and filter state, while SavedStateHandle restores them after process death.

Combine filters and remember settings

Combine the search field with chips or toggle buttons for categories, status, suburb, or date range. Apply every active constraint to the original list, then sort the final result. Australian shoppers commonly build or share a Coles or Woolworths basket before a weekly shop, so a product list can combine brand, price, and availability controls with a search term. Remember the chosen sort mode and non-sensitive filters in SharedPreferences when persistence is useful. The project at My Easy Projects provides a separate implementation to compare with this structured approach.

val preferences = context.getSharedPreferences(
    "list_settings",
    Context.MODE_PRIVATE
)

preferences.edit()
    .putString("sort_mode", "name")
    .putBoolean("active_only", true)
    .apply()

Treat preferences as convenience, not as a secure datastore. In an Australian retail or finance app, filters may reveal a person’s location or spending pattern. Follow the Privacy Act 1988 and the Australian Privacy Principles by collecting only necessary data, explaining its use, and providing appropriate access and correction. Avoid storing sensitive customer details in plain preferences; keep them in an appropriate protected store and retain a visible reset control for saved filters.