Android SharedPreferences Tutorial and Example

Developing a contact list with RecyclerView

A contact list is a compact Android exercise that combines a scrolling collection, reusable rows, user actions and changing data. RecyclerView suits the job because it recycles offscreen views and processes collection updates without rebuilding the whole screen.

This project builds a Kotlin contact screen with an alphabetised list, a search field, favourite and call buttons, and support for both in-app records and contacts held by Android. The architecture stays small enough for beginners while showing patterns used in production apps.

Each record owns a stable identifier, display name, phone number and optional email address. The UI receives immutable copies through a ViewModel, while an adapter converts those objects into visible rows and DiffUtil calculates what changed.

Australian phone formatting matters from the first sample. Keep domestic mobile numbers grouped as 04xx xxx xxx, but store an international version such as +61 4xx xxx xxx after dropping the trunk zero. Sydney, Melbourne, Brisbane and Perth sit in different time zones, with daylight-saving rules varying by region.

Plan the project and contact model

Create a single-activity project, enable View Binding and add the AndroidX RecyclerView, core-ktx and Material dependencies. Use a ConstraintLayout activity containing a TextInputLayout for search, a RecyclerView below it, and an empty-state TextView that appears when no records match.

The list should fill the available space, keep its width constrained to the parent and give the search field enough room for large font settings. Avoid a fixed row height; varied names and accessibility text need room to expand.

Start with one primary phone number per contact. A production data model can use separate phone, email and postal-address records linked to a person by foreign keys.

data class Contact(
    val id: Long,
    val displayName: String,
    val phoneNumber: String,
    val email: String = "",
    val isFavourite: Boolean = false
)

Build a practical contact row

Create item_contact.xml with a card or constrained row containing an initials image, name, phone label, favourite toggle, call button and message button. Keep decorative icons in ImageViews with useful content descriptions, such as “Call Maya Chen”.

Use stable view IDs across the row so the adapter can bind efficiently. Put the name and number in vertical chains, let long text wrap, and keep interactive targets at least 48dp. Respect dark theme colours and do not signal favourites through colour alone.

Names can contain macrons, apostrophes or hyphens, so preserve the original characters and sort with a Collator rather than raw ASCII order. The same approach supports names from many communities represented in Australian contact lists.

Connect the list to a RecyclerView

Connect the activity to the adapter with LinearLayoutManager. Pass click lambdas into the constructor so calling, messaging or favouriting remains the activity’s responsibility, while the adapter only renders state and forwards actions.

ListAdapter provides asynchronous diffing and stable change animations. Keep every contact ID unique and stable, and update the favourite indicator inside bind rather than calling notifyDataSetChanged, which would discard the benefits of RecyclerView.

A compact Kotlin adapter can be organised as follows:

class ContactAdapter(
    private val onCall: (Contact) -> Unit,
    private val onMessage: (Contact) -> Unit
) : ListAdapter<Contact, ContactAdapter.Holder>(Diff) {

    inner class Holder(val binding: ItemContactBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: Contact) {
            binding.contactName.text = item.displayName
            binding.contactNumber.text = item.phoneNumber
            binding.callButton.setOnClickListener { onCall(item) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        Holder(ItemContactBinding.inflate(
            LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: Holder, position: Int) =
        holder.bind(getItem(position))

    override fun getItemId(position: Int) = getItem(position).id

    companion object {
        val Diff = object : DiffUtil.ItemCallback<Contact>() {
            override fun areItemsTheSame(a: Contact, b: Contact) =
                a.id == b.id

            override fun areContentsTheSame(a: Contact, b: Contact) =
                a == b
        }
    }
}

The full adapter can also bind initials, favourite state and the message action. Toggle the favourite in the ViewModel, then submit the updated immutable list; ListAdapter will animate only the affected records.

Load and edit contacts safely

Choose the source deliberately. In-app contacts belong in Room or another SQLite-backed repository. Contacts already on the device require READ_CONTACTS in the manifest and a runtime permission request; explain why before the system dialog appears, and handle denial without breaking manual entry.

A ContentResolver query against ContactsContract can return duplicate people because one person may have several phone records. Normalise and merge those rows before displaying them, while retaining the original contact provider IDs if edits must be written back.

Keep disk and ContentResolver work on Dispatchers.IO, expose results as StateFlow or LiveData, and let the adapter receive them on the main thread. Save edits transactionally, refresh from the provider when needed, and distinguish a deleted system record from a failed local write.

Add search, grouping and actions

Search should compare a normalised name, number and email while showing the untouched value in the row. Lowercase with Locale.ROOT, remove formatting characters for matching, and debounce keystrokes so a large address book does not trigger a diff for every character.

Use section headers for initials, a fast-scroll thumb for long lists, and a favourite filter. ConcatAdapter can join an index adapter with contacts, although a single adapter with explicit header types is often simpler for a beginner project.

Call and message actions can launch ACTION_DIAL and ACTION_SENDTO with a tel: or smsto: URI, avoiding direct-call and SMS permissions when the user completes the action elsewhere. Australian emergency access should be prominent but deliberate: 000 and 112 both reach emergency services, so never auto-dial them. Friendly copy such as “No worries, no contacts found” also suits an Australian audience.

Test and compare the implementation

On Google Play, the Australian audience spans current flagships and lower-cost phones, so test across several Android versions, manufacturers and memory limits. Release an Android App Bundle, profile scrolling with thousands of fake contacts, and check large fonts, landscape mode and TalkBack.

Local business records may need an organisation, role, state abbreviation, suburb and postcode. These details help contacts around Adelaide, Canberra and regional centres remain recognisable. The tutorial publisher also provides implementation support; readers can contact the site team before publishing unusual choices.

The final comparison highlights the practical differences:

Concern ListView RecyclerView
View reuse Built in, but less explicit Adapter and view holders make reuse explicit
Data changes Often needs broader invalidation DiffUtil targets changed records
Row design Works well for one simple layout Supports multiple view types and animations
Setup Straightforward for small static lists More setup, better for dynamic collections

Choose RecyclerView when the screen needs explicit view types, predictable updates or richer interactions. The sample remains approachable because each responsibility has a clear home: the model stores data, the repository loads it, the ViewModel exposes state, and the adapter renders rows.