1

I found another post about this on here, but the solution did not work.

So I've got the following Kotlin code in a Singleton utility class

fun getAllFoodEvents(): MutableSet<String> {
    return sharedPrefs.getStringSet(FOOD_EVENTS_KEY, HashSet<String>())
}

fun removeFoodEvent(foodEvent: FoodEvent) {
    val events = getAllFoodEvents()
    events.remove(foodEvent.toString())
    saveAllFoodEvents(events)
}

And I've gone through all the following permutations of saveAllFoodEvents() and none of them have persisted changes across restarts. (I have tried switching out .apply() for .commit() at every stage as well)

fun saveAllFoodEvents(events: Set<String>) {
    val editor = sharedPrefs.edit()
    editor.remove(FOOD_EVENTS_KEY)
    editor.putStringSet(FOOD_EVENTS_KEY, events)
    editor.apply()
}
fun saveAllFoodEvents(events: Set<String>) {
    val editor = sharedPrefs.edit()
    editor.remove(FOOD_EVENTS_KEY)
    editor.putStringSet(FOOD_EVENTS_KEY, HashSet<String>(events))
    editor.apply()
}
fun saveAllFoodEvents(events: Set<String>) {
    val editor = sharedPrefs.edit()
    editor.remove(FOOD_EVENTS_KEY)
    editor.putStringSet(FOOD_EVENTS_KEY, HashSet<String>())
    editor.apply()
    //I thought for sure this would work, 
    //considering it seems like it should be overkill
    val editor1 = sharedPrefs.edit()
    editor1.remove(FOOD_EVENTS_KEY)
    editor1.putStringSet(FOOD_EVENTS_KEY, HashSet<String>(events))
    editor1.apply()
}

However, I have been able to get it working with a very cumbersome workaround of saving all data in various shared preferences into local variables, calling editor.clear(), and then readding all the values.

Surely this is not the intended behavior of SharedPreferences?

lbenedetto
  • 2,022
  • 1
  • 21
  • 39
  • 1
    Creating the new `HashSet(events)` should work, but I think the `editor.remove()` call might be causing the unexpected behavior, in that case. I'd have to check the source to see exactly why, but try removing the `editor.remove(FOOD_EVENTS_KEY)` line in your second example. – Mike M. Apr 22 '18 at 08:59
  • Nope, that didn't fix it – lbenedetto Apr 22 '18 at 09:06
  • 1
    OK, then create the new `HashSet` immediately from the `getStringSet()` return, then modify and save that new instance. – Mike M. Apr 22 '18 at 09:10
  • Yeah that fixed it. Thanks! – lbenedetto Apr 22 '18 at 09:17
  • 1
    Cool. The docs do explicitly state that you shouldn't modify the returned `Set`, but I would've thought the new instance in the `putStringSet()` call would have the same effect as creating one from the start. Guess I'll have to look at the source to figure that one out. Glad you got it working. Cheers! – Mike M. Apr 22 '18 at 09:24

0 Answers0