Simple Implementation of Android Preferences DataStore
DataStore is a relatively new method for storing persistent key-value data in Android, intended to be a better replacement of SharedPreferences.
There are 2 types of DataStore:
- Preferences DataStore
- Proto DataStore (or DataStore Typed)
In this first article we will make a simple application that demonstrates the usage of the first type of DataStore, Preferences DataStore.
Where’s the source code?
tl;dr
a. About DataStore
There key benefits of using DataStore instead of SharedPreferences, in my opinion, are as follows:
- DataStore uses Flow (Flow is quite similar with LiveData where you can observe a value every time it changes). SharedPreferences doesn’t have built-in support for Flow.
- Proto DataStore offers type safety. SharedPreferences (and Preferences DataStore) doesn’t have type safety.
b. About Preferences DataStore
Here’s Preferences DataStore in action:
As you can see above, with Preferences DataStore, this app persists several primitive data types:
It is also possible to persist these primitive types as well: Double
, Float
, Long
, and Set<String>
.
Step by Step Explanation
Here’s how you make the application shown in image above.
1. Open Android Studio. Create new project with “Empty Activity” option.
2. Add datastore-preferences
and lifecycle-runtime-ktx
dependencies in your app/build.gradle
file. We need Lifecycle library because we need to use Coroutine to be able to use Flow.
3. Next up, is building the layout, activity_main.xml
. Here’s what it looks like and the code needed below:
4. Lastly, we are going to update the MainActivity.kt
. You can copy paste the code below directly, but here’s the summary of how it works. First, we obtain the DataStore object using preferencesDataStore
. Then for each primitive data types (Int
, String
, and Boolean
), we retrieve previous stored DataStore value and also set a listener for updating the DataStore value.
5. That’s it! Now run the app on your device and try it for yourself. Try updating the values several times and then closing the app. When you reopen the app, the values should be persisted.
Thanks for reading!