How To Use DataStore Preference for Android Development

Tochukwu Munonye
HackMobile
Published in
3 min readDec 15, 2020

--

The Jetpack Datastore is a data storage solution that allows you to store small amounts of data in key-value pairs. It makes use of coroutine and flow to store data asynchronously. There are two ways to implement datastore;

  • Preference Datastore: This stores and accesses data using keys. It does not provide type safety and does not require a predefined schema.
  • Prototype Datastore: This implementation requires you to define a schema using protocol buffers, but it provides type safety.

This article will be about Preference Datastore, which is a replacement for the now deprecated Shared Preferences.

First of all, to use Jetpack datastore in your app, add the following dependency to your gradle file { implementation “androidx.datastore:datastore-core:1.0.0-alpha05" }. You can check the documentation for the latest dependency, incase this one is outdated.

In this article we’ll implement datastore preference in a simple way. We’ll enter a value with a key in the editText at the top of the screen, then click the save button to save the value. Then at the bottom screen, we will make the value appear on the textview when we enter the same key and click on button “Read”.

  • In the main activity we will setup our view binding, then we’ll create a variable datastore and assign it to createDatastore. In the constructor we’ll give it a name “setting”.

Then we’ll create two functions, one function to save data into the datastore and another function to read from it. The PreferencesKey is a special key we need to write into our datastore instance. In the read function we’ll only need our key which would return a nullable string. We can then read our saved values from datastore data which is a “Flow” of preferences. We’ll call .first() on it to get the first emission of the flow.

In onCreate we’ll call setOnClicklistener on button “save” to save the key and the value. Because we want to execute it from a coroutine, we’ll launch a lifecycleScope. Then we’ll setOnClicklistener to button “Read” and also launch another lifecycleScope. We’ll assign the read function to the variable value then assign assign the value to the textview.

Happy Coding!

--

--