Android SharedPreferences Tutorial and Example

Implementing SharedPreferences For Persistent Settings

Android apps often need to remember small pieces of user information after the app closes. A dark theme choice, notification preference, selected language, or dismissed welcome message should not disappear every time the user returns. SharedPreferences provides a straightforward way to store these simple settings locally.

For beginner Android developers, this API is useful because it requires no database schema, network connection, or complicated storage layer. Values are saved as key-value pairs in an XML file managed by Android, making the approach suitable for lightweight configuration data.

A settings screen in an Australian shopping, transport, or community app might remember whether a user prefers kilometres, Australian dollars, or promotional notifications. Someone using the app in Sydney or Perth expects those choices to remain available after switching between Wi-Fi and mobile data.

SharedPreferences works best when the stored information is small and uncomplicated. It is not intended for customer records, large collections, or relational data. For newer Android projects, Jetpack DataStore is often preferred for robust settings storage, but SharedPreferences remains common in tutorials, existing applications, and small projects.

Storage option Suitable data Main strength Main limitation
SharedPreferences Booleans, strings, numbers Simple implementation Limited type and data support
DataStore App preferences and structured settings Safer modern API Requires newer patterns and libraries
SQLite or Room Records and collections Queries and relationships More setup than settings require

Choose Settings And Keys Carefully

Start by deciding exactly what the application must remember. Typical examples include dark_mode, notifications_enabled, display_name, and distance_unit. Keys should be descriptive, stable, and centralised so that a spelling mistake does not create a second setting accidentally.

Kotlin constants make those keys easier to reuse throughout an activity or fragment:

private const val PREFS_NAME = "app_settings"
private const val KEY_DARK_MODE = "dark_mode"
private const val KEY_NOTIFICATIONS = "notifications_enabled"
private const val KEY_DISTANCE_UNIT = "distance_unit"

Create the preferences file with a private mode. The file belongs to the app and is unavailable to other applications on the device. Avoid placing passwords, access tokens, or private customer data in this file because SharedPreferences is not designed as encrypted storage.

val preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)

For a modern Kotlin project, keep the storage code in a small repository or helper class rather than spreading direct preference calls across every screen. This makes later migration to DataStore easier and gives the interface a single source of truth.

Save And Read Persistent Values

To save a setting, call edit(), assign a value, and finish with apply() or commit(). apply() updates the in-memory value immediately and writes to disk asynchronously, which is generally appropriate for a settings screen. commit() writes synchronously and returns a success result, but it should not be used on the main thread for routine UI changes.

preferences.edit()
    .putBoolean(KEY_DARK_MODE, true)
    .putBoolean(KEY_NOTIFICATIONS, false)
    .putString(KEY_DISTANCE_UNIT, "kilometres")
    .apply()

Read each value with the getter matching its type. Always provide a sensible default so a new installation behaves correctly before the user has opened the settings screen.

val darkMode = preferences.getBoolean(KEY_DARK_MODE, false)
val notificationsEnabled = preferences.getBoolean(KEY_NOTIFICATIONS, true)
val distanceUnit = preferences.getString(KEY_DISTANCE_UNIT, "kilometres")

Defaults should reflect the product’s expected Australian audience where relevant. For example, an app displaying distances can begin with kilometres, while a marketplace can display prices in Australian dollars. A default should describe the normal experience, not hide a missing or invalid preference.

Connect Preferences To The User Interface

A SwitchMaterial or SwitchCompat control is a natural choice for boolean preferences. Load the stored value before assigning the listener; otherwise, setting the initial checked state can trigger a write as the screen is created.

binding.darkModeSwitch.isChecked =
    preferences.getBoolean(KEY_DARK_MODE, false)

binding.darkModeSwitch.setOnCheckedChangeListener { _, enabled ->
    preferences.edit()
        .putBoolean(KEY_DARK_MODE, enabled)
        .apply()

    applyTheme(enabled)
}

For a text or selection setting, use a Spinner, radio group, or Material exposed dropdown. Store a compact value such as "kilometres" rather than saving a label that may later change. The visible label can be localised without breaking existing preferences.

When the setting affects the entire application, apply it early. A theme preference should be read before the activity inflates its main layout where possible. A notification preference should be checked before scheduling reminders. This prevents a noticeable flash of the wrong appearance and avoids creating behaviour that contradicts the saved choice.

Preserve State Across Screens And Navigation

SharedPreferences is available to different activities and fragments when they use the same preference file name. A settings fragment can save the value, while the home screen reads it during onCreate() or onResume(). If a value can change while a screen is visible, refresh the UI when the screen resumes rather than assuming its original state remains current.

Navigation also influences how settings feel. A user may open Settings from a profile screen, change the notification option, and return using the system back button or an app bar arrow. Understanding navigation back behaviour helps keep the back stack predictable and prevents duplicate destinations or stale screens.

Do not treat navigation arguments as a replacement for persistent storage. Arguments pass temporary context between destinations, while SharedPreferences keeps the choice after the process is stopped. Use each mechanism for its intended purpose, and reload persistent values when a destination becomes active.

Test Defaults, Updates And Removal

Test both a fresh installation and an existing installation. A fresh install should show the documented defaults, while a returning user should see the exact choices saved previously. Also test rotation, process recreation, leaving the app in the background, and reopening it after Android has reclaimed memory.

Useful checks for a settings implementation include:

  • Toggle a preference, close the app, and reopen it.
  • Change a selection and revisit the screen.
  • Verify the default value after clearing app data.
  • Confirm that unrelated settings remain unchanged.

Storage bugs often come from inconsistent keys or mismatched getter types. A value saved with putString() must be read with getString(), and renamed keys need a migration strategy if the app is already distributed through the Australian market.

When a preference is permanently removed, call remove() and apply the edit. Use clear() only when the user explicitly chooses a full reset, because it deletes every value in that preference file.

A reset flow can be checked by verifying that:

  • The controls return to their default states.
  • Theme and notification behaviour update immediately.
  • A reopened screen reads the reset values.
  • The reset does not remove account or database data.

With clear keys, safe defaults, and lifecycle-aware reads, SharedPreferences gives small Android applications dependable local settings without unnecessary storage complexity.