Your Second Kotlin Android App

Aug 29 2023 · Kotlin 1.8.21, Android 13, Android Studio Flamingo | 2022.2.1

Part 3: Save Preferences

18. Explore Shared Preferences

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 17. Introduction Next episode: 19. Create a ViewModel

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 18. Explore Shared Preferences

To create a to-do list, you need to save them to disk. Android comes with lots of different ways to save data. In fact, we have an entire course on saving data that is a part of the Android Learning Path.

The first and simplest way to save data is by using Shared Preferences that is often referred to as Shared Preferences. Shared Preferences is designed to save a small amount of data. You may think that Shared Preferences are only meant to share preference data, but in fact, share Preferences are meant to cover any data. For instance, if you were writing a book reading app, you may use Shared Preferences to save the user’s current reading location.

Saving is done by providing keys and values. The key is the lookup and the value is the information. You can think of it like a dictionary. In a dictionary, the word is the lookup and the definition is the value. The same works for Shared Preferences.

When saving data, you save basic types like strings, booleans, Ints, and so forth. You provide a key value like a name and then provide the value.

When you have added all your values to Shared Preferences, you save them by calling the apply method.

Retrieving the value is similar, but you get the value based on the key name.

You have already created the TaskList data class which will hold the data for each todo. You’ll now create a class that saves and reads items from Shared Preferences.

Create a new package called viewmodel and create a new class named ListDataManager.

First, create a constructor. Since Shared Preferences require a context, have the constructor require one as well.

class ListDataManager(private val context: Context) {

}

Your context is showing up in red so you can alt-enter it to import the context.

Now for the saving.

Add the following method to the class:

fun saveList(list: TaskList) {

}

This just defines the TodoList that you want to save. First, get your preferences, and set them to edit.

val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit()

Right away, you get a strike through your preference manager. You’ll also see it in yellow. This is a warning and when you check it out, it says, PreferenceManager is deprecated. The actual preference manager isn’t deprecated, it’s been migrated to Androidx.

Open a browser and head to the following URL:

https://developer.android.com/jetpack/androidx/migrate/class-mappings

You can find the class mappings from the Support Library to AndroidX here.

Search for PreferenceManager. You’ll see that it’s in the androidx.preference package.

Next over head over to the following URL:

https://developer.android.com/jetpack/androidx/migrate/artifact-mappings

Search for androidx.preference and you can see that the build artifact is androix.preference:preference. Copy it and open your build.gradle file. In the dependencies, add the following:

implementation 'androidx.preference:preference-ktx:1.2.0'

1.2.0 is the latest version at the time of recording this course.

Click the Sync Now button and switch back to the ListDataManager class.

Change the import statement to the following:

androidx.preference.PreferenceManager

With that, you can now use your preference manager.

Next, you want to save the list of tasks in your to-do list. You’ll use the name of the list as the key and then you’ll pass the list. There is a problem. The PreferenceManager doesn’t save arraylists. Thankfully, it does save sets. A set is like an array list but it doesn’t contain duplicates so you need to convert the list to a set.

Add the following code to saveList.

sharedPrefs.putStringSet(list.name, list.tasks.toHashSet())

Finally, to save, you must apply the changes.

sharedPrefs.apply()

Now to read the lists. Add the following method:

fun readLists(): ArrayList<TaskList> {

}

When called, this method will return an array of task lists. To get this to work, first, you need to get your preferences:

val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)

Next, you need to get the contents. The contents contain a map of keys and values. Then create a list to hold all of your task lists.

val contents = sharedPrefs.all
val taskLists = ArrayList<TaskList>()

With everything set, you iterate through the keys.

for (taskList in contents) {

}

First, you get the saved hashset and convert it into an arraylist

val taskItems = ArrayList(taskList.value as HashSet<String>)

Then you create the tasklist from it

val list = TaskList(taskList.key, taskItems)

And add it to the array.

taskLists.add(list)

Finally, you return your task lists

return taskLists

You now have a class that can read and write data. Well done!