DEV Community

Cover image for How To use DataStore Preferences In Android App Using Kotlin
Karim Abdallah
Karim Abdallah

Posted on

How To use DataStore Preferences In Android App Using Kotlin

In

this tutorial i will show you how to use DataStore Preferences to save data locally in your android application instead of the old method with Shared Preferences.

I See A lot Of People That Didn't Know How to use DataStore and they see it's too difficult, so in this article i will explain everything in DataStore to make it Easier For You So Please save this post and And focus with me 😁


.

What Is DataStore Preferences?

DataStore is a data storage solution that allows you to store key-value pairs or typed objects with protocol buffers. DataStore uses Kotlin coroutines and Flow to store data asynchronously, consistently, and transactionally.

i know that you didn't understand the context but let's begin now!


In This Article We Will Create A Simple App That Will Save User Name & Email Address, Here Is The Project Source Code On Github


you can also download a demo app from github actions to see how the app works: demo app

app preview

Let's Start NOW ⚽


1. Create A New Project On Android Studio.

2. Open build.gradle file and add the library implementation:

Check the latest version of the library from google developers


3. Create A New Class Called DataStoreManager for example, and Create Init Of The DataStore:

We Need to stop here to understand what is going on with the previous code.

dsInit

look at this image and let's explain it:
1- this is the name of the datastore pref that we will use it to make actions on this dataStore Name.
2- the second one is the DataStore name Let's Say it's like Database Name like SQL that we will use to store data with this name.


4. Now Let's Create Keys That Will Save The Data Inside The DataStore That we've created:

Here i've created two keys one for store Username, the other will store Email address.


Now We're Ready To Use DataStore In Our Activity/Fragment.

I've Created a simple app that contains two EditTexts & two Buttons and two textViews That Will Display The Saved Data, You Can Find The Sample Project At Github.


5. Now Open Your Activity And Create a Suspend Fun That Will Save Our Data From The Edittexts:

Wait, What Is Going On Here?

First, DataStore Runs Only Inside suspend fun or CoroutineScope so that's why i've created suspended fun.

After That I've Created instance of user that we've declared it before by calling:

user.edit { usrData ->

}
Enter fullscreen mode Exit fullscreen mode

usrData is a value-parameter you can choose any name because it's a lambda expression.


And inside the user.edit expression i've added the keys that we've created before to save the name and email:

user.edit { usrData ->
    usrData[DataStoreKeys.USER_NAME] = name
    usrData[DataStoreKeys.EMAIL] = email
}
Enter fullscreen mode Exit fullscreen mode


Now You Have Successfully Saved Data Using DataStore 🎉, it's simple right?


6. Let's Create A New Function That Will Get The Saved Data And Display It In Our UI:

Explaination:
As We Explained Before We've Added The user instance but here in GetData you will use user.data.collect to collect saved data is it Exists if there is no data saved it will return null so that's why i've added ?: "none" to check if the datastore returned null the null check will return "none" value.

And as we know we can retrive data by the same keys we used to save data so you will use it again to retrive data again:

user.data.collect { usrData ->
    val name = usrData[DataStoreKeys.USER_NAME] ?: "none"
    val email = usrData[DataStoreKeys.EMAIL] ?: "none"

    // you can use $name variable or $email anywhere
}
Enter fullscreen mode Exit fullscreen mode

as i told you before i've added ?: "none" to check if the datastore returned null it will return "none" instead of null to prevent App Crashes.


7. The Last Step Is Creating A Function That Will Delete The Saved Data:

Explaination:
It's Simple Just Use The user instance and use user.edit to access the DataStore And call usrData.clear():

user.edit { usrData ->
    usrData.clear()
}
Enter fullscreen mode Exit fullscreen mode


You Can Use All These Functions At OnCreate Inside CoroutineScope(Dispatchers.IO) like that:

CoroutineScope(Dispatchers.IO).launch {
    getUserData()  //get data suspend fun
}
Enter fullscreen mode Exit fullscreen mode


That's All For Today, Thanks For Reading, Please Share & Follow For More :)


Resources:
https://developer.android.com/topic/libraries/architecture/datastore

https://github.com/kimoandroid/DataStore-Android-Example




The Full MainActivity Code:

Top comments (0)