Android SharedPreferences Tutorial and Example

Saving user preferences with Android DataStore

Android DataStore provides a modern way to persist small pieces of user configuration, including a selected theme, a favourite city, or whether onboarding has been completed. It replaces ad-hoc file and preference handling with typed keys, asynchronous disk access, and a Kotlin Flow that can react when values change.

For most settings, choose Preferences DataStore rather than Proto DataStore. Preferences suits simple values such as strings, booleans, integers, longs, floats, and sets, while keeping the implementation approachable. Proto DataStore is useful when a typed schema or serialisable object is required, but it adds unnecessary ceremony for a handful of app settings.

The design below places storage behind a repository so activities, fragments, and composables never touch DataStore directly. It also gives one place to handle read failures, coordinate updates, and move existing SharedPreferences data into the new system without blocking the user interface.

Understanding where preferences belong

DataStore is local device storage, not cloud synchronisation. If a commuter in Melbourne changes a favourite tram stop, that choice can be read quickly on the next launch, but another device will not receive it unless your application uploads it separately. Keep server-backed profiles and cross-device accounts out of this layer.

An app used around Sydney might remember a train station, while a meditation app could store a preferred session length. These are isolated key-value choices, not relational records. For structured information that needs sorting, filtering, joins, or complex transactions, a database remains the better fit.

Friendly Australian copy can say “No worries, you’re set” after a preference is saved, but stable technical names should stay consistent in code. Localised display text can change; the stored key and its meaning should not.

Adding the DataStore dependency

Add the AndroidX artifact to the module that owns the data layer. Use the current stable release approved by your project; this sample shows a common baseline:

dependencies {
    implementation("androidx.datastore:datastore-preferences:1.1.1")
}

Declare one Preferences DataStore for the application process. A top-level delegate creates and reuses the same instance for a given Context:

val Context.userPreferencesStore by preferencesDataStore(
    name = "user_preferences"
)

Store this delegate in a small file, inject it into your repository, and avoid creating another DataStore for the same file. Multiple active instances for one file in one process can trigger exceptions, while one shared instance keeps reads and writes consistent.

Creating a typed repository

A typed layer prevents string-based key mistakes. Define each key once, then map the stored Preferences into an immutable data class that the rest of the app can consume.

private object PreferenceKeys {
    val city = stringPreferencesKey("city")
    val darkMode = booleanPreferencesKey("dark_mode")
    val onboardingComplete =
        booleanPreferencesKey("onboarding_complete")
}

data class UserPreferences(
    val city: String = "",
    val darkMode: Boolean = false,
    val onboardingComplete: Boolean = false
)

Expose the mapped values as a Flow. The mapper performs no disk write, so it can react safely to changes made elsewhere in the application.

class PreferencesRepository(
    private val dataStore: DataStore<Preferences>
) {
    val userPreferences: Flow<UserPreferences> = dataStore.data
        .catch { exception ->
            if (exception is IOException) {
                emit(emptyPreferences())
            } else {
                throw exception
            }
        }
        .map { preferences ->
            UserPreferences(
                city = preferences[PreferenceKeys.city] ?: "",
                darkMode = preferences[PreferenceKeys.darkMode] ?: false,
                onboardingComplete = preferences[
                    PreferenceKeys.onboardingComplete
                ] ?: false
            )
        }
}

The repository can be created in your Application class or supplied through dependency injection. That arrangement survives configuration changes and keeps Android-specific storage details out of the UI layer.

Reading preferences safely

Collect repository.userPreferences with lifecycle awareness. In a View-based screen, launch a coroutine tied to the STARTED lifecycle; in Compose, use collectAsStateWithLifecycle. The Flow emits the current values and then updates when an edit completes, so the interface can display the saved theme or station without polling.

Use first() for a one-time read, such as deciding which screen to open at launch. Handle IOException around the data Flow so an unreadable file does not crash the app. Preferences DataStore is not a query engine; for query-heavy records, the SQLite example guide shows how a relational approach differs.

Mechanism Best suited to Access style Main caution
SharedPreferences Small legacy flags Synchronous getters and editors Avoid main-thread work and plan a migration
Preferences DataStore Current app settings and preferences Suspend functions plus Flow Not designed for relational queries
SQLite Structured records needing queries SQL cursors and transactions Requires schema and careful migration code

Writing preferences consistently

All writes go through the suspend edit function. Because it performs file I/O away from the main thread, call it from a coroutine and never wrap it in runBlocking on the UI thread.

suspend fun saveCity(value: String) {
    dataStore.edit { preferences ->
        preferences[PreferenceKeys.city] = value
    }
}

Group related values into one edit call when they must change together. DataStore serialises its transformations, and applying a group in one operation avoids partially updated application state.

For simple independent switches, separate edit calls are acceptable. Give every write a clear owner, expose suspend functions rather than mutable Preferences objects, and let the UI react to the resulting Flow instead of maintaining a second, conflicting copy of the truth.

Migrating SharedPreferences values

A migration should read the old SharedPreferences values, write them to DataStore, and only then remove the legacy entries. This order prevents data loss if the process stops between stages.

val legacy = context.getSharedPreferences(
    "legacy_settings",
    Context.MODE_PRIVATE
)
val city = legacy.getString("city", null)

if (city != null) {
    repository.saveCity(city)
    check(legacy.edit().remove("city").commit())
}

Run the migration on a background dispatcher and make it idempotent, so running it twice does no harm. Handle each value that needs conversion rather than assuming old keys and new keys have identical formats. If a write fails, retain the SharedPreferences copy for the next attempt.

Remove the old dependency only after migration coverage is verified. Test upgrades with real legacy files, including empty values, missing keys, and unexpected data types. The same migration path should work when an existing user updates through Google Play.

Testing and preparing for release

Test the repository independently with a temporary Preferences DataStore, then add an instrumented test that launches the app, changes a setting, forces the process to stop, and confirms the value remains. Also test a failed read, an interrupted migration, and the default state on a fresh install.

Watch backup and restore behaviour during release checks. Android may restore app data to a replacement handset, which can incorrectly skip onboarding. If that is undesirable, exclude the relevant DataStore file with backup rules or reset device-specific keys after restoration. Test upgrades from versions that still use SharedPreferences before publishing through Google Play, the official Android app store on devices sold in Australia.

Local storage does not remove privacy obligations. If a preference contains a name, location, or another identifiable detail, document its purpose, apply the Australian Privacy Principles under the Privacy Act 1988 where applicable, and avoid collecting more than the feature needs. An Australian release may combine local settings with Melbourne or Sydney location data, so consent and deletion remain product requirements.

A repository built this way keeps disk access off the UI thread, gives screens one observable source of truth, and leaves room for both legacy upgrades and careful privacy reviews.