![]() |
VOOZH | about |
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.
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
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")
}
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:
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:
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: