Save User State

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Koala | 2024.1.1

Lesson 01: Save Simple Data

Demo: Create & Setup DataStore

Episode complete

Play next episode

Next
Transcript

Open the Starter project in the 01-save-simple-data directory of the m3-sua-materials repo in Android Studio Hedgehog or later.

Wait for the project to be built.

To be able to use DataStore in your project, you need to add the following dependencies to your app’s build.gradle file:

dependencies {
  implementation "androidx.datastore:datastore-preferences:1.1.1"
}

Tap the Sync Now button that appears in the top-right corner of the IDE to sync the dependency. Now, your project is ready to use DataStore!

Head over to the data package. Inside data, create a new package called datastore. This will host the class and handle all your DataStore operations. Inside the datastore package, create a new class called DataStoreManager. Start by creating a constructor for the DataStoreManager class. The constructor takes Context as a parameter. Next, create a new DataStore instance at the top of the class that will be used in this class to perform read and write operations to DataStore. Your class declaration and DataStore instance will look like the following code:

class DataStoreManager(private val context: Context) {

  private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "devscribe")

}

In the code above, you created a property whose receiver type is Context. You then delegated its value to preferencesDataStore(). preferencesDataStore() takes the name of the DataStore as a parameter.

As you add code to the project, you’ll need to add the associated imports. For instance, the context reference above needs to import android.content.Context. Right-click Context, click Show context actions, and click Import class 'Context'. This will add the following line to your imports section:

import android.content.Context

Be sure to add the following imports when the IDE prompts you to do so:

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore

Your DataStore instance is now ready to be used in your app. In the next section, you’ll work on saving data to DataStore.

See forum comments
Cinema mode Download course materials from Github
Previous: Introduction to DataStore Storage Solution Next: Write Data to DataStore