Android SharedPreferences String Set - some items are removed after app restart

前端 未结 6 1996
南笙
南笙 2021-02-03 19:38

I save a string set in the shared preferences, if I read it out it\'s ok. I start other activities, go back and read it again, it\'s ok. If I close the application, and start it

6条回答
  •  孤街浪徒
    2021-02-03 20:22

    This "problem" is documented on SharedPreferences.getStringSet().

    getStringSet() returns a reference of the stored HashSet object inside SharedPreferences. When you add elements to this object, they are added in fact inside SharedPreferences.

    The workaround is making a copy of the returned Set and putting the new Set into SharedPreferences. I tested it and it works.

    In Kotlin, that would be

        val setFromSharedPreferences = sharedPreferences.getStringSet("key", mutableSetOf())
        val copyOfSet = setFromSharedPreferences.toMutableSet()
        copyOfSet.add(addedString)
    
        val editor = sharedPreferences.edit()
        editor.putStringSet("key", copyOfSet)
        editor.apply() // or commit() if really needed
    

提交回复
热议问题