Shared Preferences | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/7503473-your-second-kotlin-android-app/lessons/15

Data error (cyclic redundancy check)

Hey, upon following the instructions of the video, both in the video and my IDE android studio flags the line ā€˜val taskItems = ArrayList(taskList.value as HashSet)ā€™ with an unchecked cast exception, which is preventing me from building and running the app. I canā€™t find a way around this, as all the other data collections give me the same error, they want the type arguments as Any rather than String.

Any advice?

Thanks,
Stefan

Nothing inside fun saveList seems to work correctly for me. I thought I may have done the preferencemanager importing wrong, but I did it again and still have the same issues.

in the line where Brian says we must convert the list to a set, the putStringSet method appears to me as an unresolved reference and asks me to rename it.

also in the last line, where it reads sharedPrefs.apply() android studio asks me to ā€˜create extension functionā€™ and suggests a complete different syntax for it.

I also have an issue which was mentioned in a previous comment by stefannovak

Thanks in advance for any advice.

You are welcome to send me your project to brian@razeware.com and Iā€™ll take a look at the issue and see whatā€™s going on.

@stefannovak @claudiom24 Do you still have issues with this?

Iā€™m having a similar issue:
package com.raywenderlich.listmaker

import android.content.Context
import androidx.preference.PreferenceManager

class ListDataManager(private val context: Context) {
fun saveList(list: TaskList) {
val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
sharedPrefs.putStringSet(list.name, list.tasks.toHashSet())
}
}
the ā€œputStringSetā€ is red saying ā€œunresolved referenceā€

SDK 30
Build Tools 30.0.1

I think the code needs to look something like the following. Replace the commented line with the following 2 lines and the apply is a method on the editor.

fun saveList(list: TaskList) {
    val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
    //sharedPrefs.putStringSet(list.name, list.tasks.toHashSet())
    var editor = sharedPrefs.edit()
    editor.putStringSet(list.name, list.tasks.toHashSet())
    editor.apply()
}

What is HashSet and why use this?

Iā€™m aware this is an old comment, but I thought I would answer anyway since others might run into the same issue. In order to modify preferences, we need to get a new, editable copy of SharedPreferences, which can be accessed by going sharedPrefs.edit(). This returns an Editor object that you can now call putStringSet() on. Note that you will also need to call apply() in order to commit these changes back to our original SharedPreferences object: sharedPrefs.edit().putStringSet(...).apply()