VOOZH about

URL: https://www.geeksforgeeks.org/android/preferences-datastore-in-android/

⇱ Preferences DataStore in Android - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Preferences DataStore in Android

Last Updated : 23 Jul, 2025

Preference Data Store is used to store data permanently in android. Earlier we had to Shared Preferences for the same but since it is deprecated we are using Data Store now. A sample video is given at the end to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.

Step by Step Implementation

Step 1: Create a new project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Note that select Kotlin as the programming language

Step 2: Add dependency inside build.gradle(app)

Add the Data Store and Livedata dependency inside the build.gradle.kts (Module :app) and click on the sync now button.

dependencies {
...
implementation ("androidx.datastore:datastore-preferences:1.1.6")

// livedata - optional
implementation ("androidx.lifecycle:lifecycle-livedata-ktx:2.8.7")
}


Step 3: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. This is for the basic layout used in the app.

activity_main.xml:


Step 4: Working with the UserManager.kt class

Create a new kotlin class and name it UserManager, this class holds the code for saving and retrieving data from the preference Data Store. Comments are added inside the code to understand the code in more detail.

UserManager.kt:


Step 5: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

MainActivity.kt:

Output:


Comment
Article Tags:

Explore