首页 > 解决方案 > SharedPreference 没有保存最后添加的 stringSet

问题描述

当我尝试将 stringSet 中的第一个字符串保存到它正常保存的 sharedPreferences 时,但在尝试在 stringSet 中保存另一个字符串后,它显示好像它已保存但重新启动应用程序并检索数据时,它只显示第一个字符串已保存,当我再次尝试单击相同的功能按钮时,它不会保存到 sharedPreferecnes,但单击具有相同功能的另一个按钮将保存我觉得奇怪的前一个按钮。这是我的代码

button.setOnClickListener {
    val orderPrefs = getSharedPreferences("order", Context.MODE_PRIVATE)
    val editor = orderPrefs.edit()
    var test = orderPrefs.getStringSet("recentlyViewedRestaurant", null)
    if (test == null) {
        test = HashSet<String>(0)
    }
    test.add(restaurantName)
    //Log.d("LastPicked", test.toString())
    editor.putStringSet("recentlyViewedRestaurant", test)
    editor.apply()
    val testing = getSharedPreferences("order", Context.MODE_PRIVATE)
    //it will retrieve and show the expected result but leaving the page
    //and retrieving from another activity won't show the last added string
    Log.d(
        "lastPicked",
        testing.getStringSet("recentlyViewedRestaurant", null).toString()
    )
}

标签: android-studiokotlinsharedpreferences

解决方案


我没有看到您在保存字符串后添加“.apply()”。

前任:

val orderPrefs = getSharedPreferences("order", Context.MODE_PRIVATE)
val editor = orderPrefs.edit()

editor.putStringSet("recentlyViewedRestaurant", test).apply()

推荐阅读