Official Google Android Developer documentation encourages using DataStore
, if you already have implemented SharedPreferences
.
It is recommended to not store complex data objects in SharedPreferences
, for complex types, consider using Room Database. But, if you still wish to procced using DataStore
for storing complex data objects, you can do it via Proto Data Store.
Add Preferences DataStore
to your project, by adding the following line in your Gradle file:
dependencies {
implementation("androidx.datastore:datastore-preferences:1.0.0")
}
Creating a Preferences DataStore
:
val Context.appPreferences: DataStore<Preferences> by preferencesDataStore("appDataStore")
You can store data in your Data Store using Key/Value pair method. Since, we are using Preferences Data Store, we have to stick storing and retrieving a primitive data type such as Int or Double, or String which isn’t Primitive but not complex either. Here is how we read from Preferences Data Store:
val getLastStoredString: Flow<String> = context.appPreferences.data.map { preferences ->
preferences["LAST_STORED_STRING"] ?: ""
}
Notice how there is no type safety while retrieving the String value, we have to provide an empty string if there is no LAST_STORED_STRING
value present.
Here is how you can write to Preferences Data Store:
suspend fun setLastStoredString(stringToSave: String){
context.appPreferences.edit { preferences ->
preferences["LAST_STORED_STRING"] = stringToSave
}
}
To store small values, Preferences Data Store is a great solution. The most real-time used application of Data Store is to set and get the default language of an application. We’ll see it in working in next part.
Leave a Reply