Sanniv Khare 7 min read

SharedPreferences to DataStore 1.3: porting app settings, tested

SharedPreferences to DataStore 1.3: porting app settings, tested

Moving settings from SharedPreferences to Jetpack DataStore is safe if you do four things: pass SharedPreferencesMigration to the DataStore, keep every key name and type exactly as it was, remove every remaining SharedPreferences writer in the same release, and create one DataStore per file. We ported a six-setting class to Preferences DataStore 1.3.0 (stable since 21 October 2026) and tested it on our M1 lab Mac with AGP 9.4.0, Gradle 9.6.0, Kotlin 2.3.21 and JDK 17: five JVM tests and one Robolectric test, all passing. The results also show the two mistakes that compile fine and fail later: reading a migrated key with the wrong type, and opening a second DataStore on the same file.

Why we did this: settings code is in every Android app we ship (Peepal, Shopkeeper and the BMDB TV app all keep a theme, flags and a few counters), and it is usually the oldest code in the project.

The setup we tested

The sample is a fresh Android app, not client code. The old class, LegacySettings, wraps a SharedPreferences file called app_settings with six values, one of each type SharedPreferences supports: a String theme, a Float font scale, an Int launch counter, a Long sync time, a Boolean notification flag and a Set<String> of pinned categories. The new code reads and writes the same values through Preferences DataStore.

# gradle/libs.versions.toml
[versions]
datastore = "1.3.0"

[libraries]
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }

datastore-preferences 1.3.0 brought in datastore-core, datastore-core-okio, datastore-preferences-core, datastore-preferences-proto, its own datastore-preferences-external-protobuf, Okio 3.17.0 and androidx.tracing 2.0.1, per ./gradlew :app:dependencies. A clean assembleDebug of the sample (Compose, Lifecycle 2.10.0 and DataStore, compileSdk 37) took 68 s on our M1 lab Mac. That is one run of a first build, not a benchmark.

Step 1: declare the store with its migration

DataStore runs migrations before the first read, so the whole port is one argument:

const val LEGACY_PREFS = "app_settings"

val Context.settingsStore: DataStore<Preferences> by preferencesDataStore(
    name = "settings",
    produceMigrations = { context ->
        listOf(SharedPreferencesMigration(context, LEGACY_PREFS))
    },
)

The top-level delegate matters. Android’s DataStore guide puts it first in its rules: “Never create more than one instance of DataStore for a given file in the same process.” A property delegate on Context gives you exactly one.

For tests we built the same store by hand, because SharedPreferencesMigration also accepts a function that returns any SharedPreferences. That is the overload to use for EncryptedSharedPreferences or direct-boot preferences too:

fun createSettingsStore(
    file: File,
    scope: CoroutineScope,
    legacy: () -> SharedPreferences,
    keys: Set<String>? = null,
) = PreferenceDataStoreFactory.create(
    migrations = listOf(
        if (keys == null) SharedPreferencesMigration(legacy)
        else SharedPreferencesMigration(legacy, keys)
    ),
    scope = scope,
    produceFile = { file },
)

Step 2: keep the keys and the types

Define the DataStore keys with the same names and the same types the old code wrote:

object Keys {
    val THEME = stringPreferencesKey("theme")
    val FONT_SCALE = floatPreferencesKey("font_scale")
    val LAUNCH_COUNT = intPreferencesKey("launch_count")
    val LAST_SYNC = longPreferencesKey("last_sync")
    val NOTIFICATIONS = booleanPreferencesKey("notifications")
    val PINNED = stringSetPreferencesKey("pinned_categories")
}

Then the setters change shape. apply() disappears; writes become suspend functions, and a read-modify-write such as a counter goes inside one edit block, which DataStore runs as a single transaction:

SharedPreferences getter and setter next to the DataStore Flow and suspend setter

The same theme setting in the old class and in the DataStore repository.

suspend fun recordLaunch() {
    store.edit { it[Keys.LAUNCH_COUNT] = (it[Keys.LAUNCH_COUNT] ?: 0) + 1 }
}

What the tests showed

We wrote an in-memory SharedPreferences for JVM tests (it counts commit() and apply() calls), filled it through LegacySettings plus one extra key the class does not know about, debug_host, and opened the DataStore on a temp file. Five JVM tests passed in about 0.12 s in total. A sixth test ran under Robolectric 4.16 on API 35 with a real Context and the real XML preferences file.

Gradle test output: keys migrated, legacy empty, stale write ignored, wrong type and second store errors

Real output from our M1 lab Mac. The lines come from println calls inside the tests.

Every key and every type survived. All seven keys arrived with their original types, including the Set<String> and the unknown debug_host: with no key list, the migration copies everything in the file. Afterwards the old preferences were empty, removed with a single commit().

A key list limits the move. With keysToMigrate = setOf("theme", "launch_count"), only those two moved and the other five stayed in SharedPreferences. Use this when part of the file belongs to another library.

A stale write after the move is ignored, then deleted. We migrated, changed the theme to light through DataStore, closed the store, then let the old class write theme = "sepia" and launchCount = 7, as forgotten code would. On reopening, the migration ran again (the old file had keys in it), but DataStore kept light and 42: the migration skips keys that already exist. It still deleted the stale values from SharedPreferences. So a leftover writer does not corrupt settings; its writes are lost without a trace. Search for every getSharedPreferences("app_settings" and PreferenceManager.getDefaultSharedPreferences before you ship.

The wrong type compiles and then throws. The counter was written with putInt. Reading it with longPreferencesKey("launch_count") compiles, then fails on read with ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long. Check old putLong timestamps and putFloat values in particular when you write the keys.

A second store on the same file fails at read time. Opening two stores on one file in one process threw IllegalStateException: There are multiple DataStores active for the same file on the second read, as the guide says. Creating a store inside a ViewModel or a repository constructor is the usual way to hit this.

With a real Context, the XML file goes away. Under Robolectric, shared_prefs/app_settings.xml existed before the first DataStore read and was gone after it, with theme = dark and launch_count = 42 readable from DataStore and datastore/settings.preferences_pb written. With the function-based overload there is no Context, so only the keys are removed; delete the file yourself if you used that path.

Step 3: read it in Compose

The guide says to avoid reading DataStore directly in composables and to go through a ViewModel with collectAsStateWithLifecycle. This compiled in our sample with Lifecycle 2.10.0:

class SettingsViewModel(app: Application) : AndroidViewModel(app) {
    private val repo = SettingsRepository(app.settingsStore)
    val settings: StateFlow<Settings> = repo.settings
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Settings())
}

@Composable
fun SettingsScreen(vm: SettingsViewModel = viewModel()) {
    val s by vm.settings.collectAsStateWithLifecycle()
    BasicText("Theme: ${s.theme}")
}

The repository’s Flow catches IOException and emits empty preferences, so a damaged file falls back to defaults instead of crashing the screen. The first frame shows Settings() defaults until the file is read; if a wrong theme for one frame matters to you, keep a splash condition on the first emission rather than calling runBlocking on the main thread.

Multi-process apps

If a service in another process (android:process=":service") reads the same settings, a plain preferencesDataStore is not enough. The guide’s rule is not to mix SingleProcessDataStore and MultiProcessDataStore for one file, and to build the store with MultiProcessDataStoreFactory in both processes. Decide this before the migration ships: once the keys have moved, the old file is empty and there is nothing left to migrate again.

The checklist we use

  1. Add datastore-preferences 1.3.0 and declare one store per file with SharedPreferencesMigration.
  2. Write the keys with the exact old names and types; check every putLong and putFloat.
  3. Replace every reader and writer of the old file in the same release, including libraries and debug screens.
  4. Move counters into a single edit block.
  5. Read through a ViewModel StateFlow in Compose.
  6. Use MultiProcessDataStoreFactory if another process touches the settings.

The DataStore 1.3.0 release notes are on the AndroidX DataStore releases page. For the Gradle side of the same kind of port, see our version catalog guide and the AGP 9.6 Kotlin plugin floor; the iOS counterpart is our Core Data to SwiftData port.

Made by the team behind this post

Apps from our studio

  • Goes with this post

    BMDB.fun

    Your Bollywood world at a glance, with links straight to the OTT app that streams each film.

    Android TV · Web · Mobile

    Get
  • Nix

    The Mac uninstaller that finds what the Trash leaves behind: caches, logs, derived data and saved states.

    macOS

    Get
  • Cardigami

    Pop-up greeting cards that rise out of the fold on iPhone Duo.

    iPhone · App Store

    Get
  • OneClick QuitAll

    Quit every running app in one click. See memory and CPU first.

    macOS · Mac App Store

    Get

Need this built? Let’s talk.

We build and run apps for Mac, TV, mobile and the web, and write about what we learn.