0

When I try to save the first string in a stringSet to the sharedPreferences it saves normally, but after trying to save another string in stringSet it shows as if it was saved but when restarting the application and retrieving the data, it only shows the first string that was saved, when I try again clicking on the same functionality button, it won't save to sharedPreferecnes, but clicking another button that have the same functionality will save the previous which I found strange. here is my code

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()
    )
}
  • You should not be modifying the stringset but a copy of it. https://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-sharedpreferences – laalto Apr 22 '21 at 12:53
  • @laalto I am reading about it, thank you for the quick response – Mohmmad Qunibi Apr 22 '21 at 12:57

1 Answers1

0

I don't see you adding ".apply()" after saving the string.

Ex:

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

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