https://kotlinlang.org logo
#compose
Title
# compose
l

Law Gimenez

07/01/2021, 8:07 AM
Hi friends, tried migrating to DataStore from SharedPreferences but
createDataStore
method not found. I already added the library on Gradle. I’m following Google’s documentation by the way
p

patrick

07/01/2021, 8:13 AM
Not sure which version you are using, but there's something about this in the Release Notes of DataStore for the `alpha07`: https://developer.android.com/jetpack/androidx/releases/datastore#1.0.0-alpha07
l

Law Gimenez

07/01/2021, 8:20 AM
Thanks I’m checking this one https://android-developers.googleblog.com/2020/09/prefer-storing-data-with-jetpack.html. Do you have any idea how to migrate from SharedPreferences using this latest syntax?
p

patrick

07/01/2021, 8:28 AM
Does this work:
Copy code
val Context.myDataStore by preferencesDataStore(
    name = "settings",
    produceMigrations = { context ->
        listOf(
            SharedPreferencesMigration(context, "settings")
        )
    }
)
?
l

Law Gimenez

07/01/2021, 8:30 AM
@patrick no it doesn’t work I’m sorry
p

patrick

07/01/2021, 8:33 AM
In your context it could look somewhat like this:
Copy code
val Context.myDataStore by preferencesDataStore(
    name = "filename",
    produceMigrations = { context ->
        listOf(
            SharedPreferencesMigration(context, "settings")
        )
    }
)

object OnlineJobPreferences{

    fun save(context: Context, jobPreferences: String){
        val dataStore = context.myDataStore
        dataStore.updateData { ... }
    }
}
You can access the datastore anywhere in your codebase by calling
myDataStore
on a context and the migration should happen automatically
l

Law Gimenez

07/01/2021, 8:36 AM
@patrick thanks your syntax worked already. Does it migrate all the stored values from my old SharedPreferences, or should do it manually?
p

patrick

07/01/2021, 8:37 AM
It should work automatically you just need to use the datastore (reading or writing) as I understood it from the docs
l

Law Gimenez

07/01/2021, 8:37 AM
@patrick appreciate the help. Thank you so much!
3 Views