How To use DataStore Preferences In Android App Using Kotlin
Tags: android, programming, androiddev, tutorial
Published: 2023-09-07 21:13:01




**<h1>In</h1> 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 😁

<br/>.
## 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!

<br/>**In This Article We Will Create A Simple App That Will Save User Name & Email Address, Here Is The [Project Source Code On Github](https://github.com/kimoandroid/DataStore-Android-Example)**

<br/>you can also download a demo app from github actions to see how the app works: [demo app](https://github.com/kimoandroid/DataStore-Android-Example/suites/15938198488/artifacts/909839080)

![app preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdsid0qbe0py76cahi3z.png)<br/>


## Let's Start NOW ⚽

<br/>**1. Create A New Project On Android Studio.**

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

{% embed https://gist.github.com/kimoandroid/e9504b4ba92cfacfac58f59853379593 %}

> Check the latest version of the library from [google developers](https://developer.android.com/topic/libraries/architecture/datastore#preferences-datastore-dependencies)

<br/>**3. Create A New Class Called `DataStoreManager` for example, and Create Init Of The DataStore:**
{% embed https://gist.github.com/kimoandroid/226440eda221220dc82abdfb0606013f %}

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


![dsInit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6lsu39wves3fgpai73ql.png)

<u>look at this image and let's explain it:</u>
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.

<br/>**4. Now Let's Create Keys That Will Save The Data Inside The DataStore That we've created:**
{% embed https://gist.github.com/kimoandroid/d695fc083a19bc1901f90c3fec5e439f %}

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

<br/>**<h3>Now We're Ready To Use DataStore In Our Activity/Fragment.</h3>**

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](https://github.com/kimoandroid/DataStore-Android-Example).

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

{% embed https://gist.github.com/kimoandroid/3246222873510274fe621808ffd675f4 %}

**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:

```kotlin
user.edit { usrData ->

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

<br/>And inside the `user.edit` expression i've added the keys that we've created before to save the name and email:
```kotlin
user.edit { usrData ->
    usrData[DataStoreKeys.USER_NAME] = name
    usrData[DataStoreKeys.EMAIL] = email
}
```

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


<br/>**6. Let's Create A New Function That Will Get The Saved Data And Display It In Our UI:**
{% embed https://gist.github.com/kimoandroid/ff6430bd84f6acd01e29b56a7a990f83 %}

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:

```kotlin
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
}
```

> 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.


<br/>**7. The Last Step Is Creating A Function That Will Delete The Saved Data:**
{% embed https://gist.github.com/kimoandroid/be100d0c98eda1cd1213143babd815a4 %}

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

<br/>You Can Use All These Functions At OnCreate Inside `CoroutineScope(Dispatchers.IO)` like that:

```kotlin
CoroutineScope(Dispatchers.IO).launch {
    getUserData()  //get data suspend fun
}
```

<br/>**That's All For Today, Thanks For Reading, Please Share & Follow For More :)**

<br/>**Resources:**
[https://developer.android.com/topic/libraries/architecture/datastore](https://developer.android.com/topic/libraries/architecture/datastore)

[https://github.com/kimoandroid/DataStore-Android-Example](https://github.com/kimoandroid/DataStore-Android-Example)

<br/><br/><br/>The Full MainActivity Code:

{% embed https://gist.github.com/kimoandroid/99431f3e43d2581e45a70c9c5595200b %}