我在这里找到another post about this,但解决方案无效。
所以我在Singleton实用程序类中获得了以下Kotlin代码
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)
}
我已经完成了以下所有saveAllFoodEvents()的排列,并且没有一个在重新启动时保持更改。 (我已尝试在每个阶段为.commit()切换.apply())
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()
}
但是,我已经能够使用一种非常麻烦的解决方法,即将各种共享首选项中的所有数据保存到局部变量中,调用editor.clear(),然后读取所有值。
当然,这不是SharedPreferences的预期行为吗?