Set <String>, losing data when restoring from SharedPreferences after restarting the application.

I am using SharedPreference on android to store a set of strings . As far as I know, it is saved and retrieved, but when the application restarts, some data is lost . Rows are added one after the other, and before adding them, I retrieve the set, add the row, and then save it again.

This is how I store it:

Set<String> emptySet = null; SharedPreferences prefs = getContext().getSharedPreferences(getContext().getString(R.string.pref_disagree_key), Activity.MODE_PRIVATE); String newIdAgreed = getItem(position).getId(); if (prefs.contains(getContext().getString(R.string.pref_disagree_key))) { Set<String> updateSet = prefs.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet); updateSet.add(newIdAgreed); SharedPreferences.Editor editor = prefs.edit(); editor.putStringSet(getContext().getString(R.string.pref_disagree_key), updateSet); editor.commit(); } else { Set<String> newSet = new HashSet<String>(); newSet.add(newIdAgreed); SharedPreferences.Editor editor = prefs.edit(); editor.putStringSet(getContext().getString(R.string.pref_disagree_key), newSet); editor.commit(); } 

And this is how I will return it:

 if (prefsDisagree.contains(getContext().getString(R.string.pref_disagree_key))){ disagree_set = new HashSet<String>(prefsDisagree.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet)); for (String item: disagree_set){ //stuff done here } } 

I saw some similar questions on this topic, but none of the answers resolved my problem. Any ideas?

+5
source share
1 answer

A StringSet is not permanent when you try to edit all this again after saving it, and therefore new data that has been added will not be saved when you exit the application and will open again.

Actually documented: getStringSet

You need to copy the StringSet first, and then paste / add data to the copied StringSet :

 Set<String> s = new HashSet<String(prefs.getStringSet( getContext().getString(R.string.pref_disagree_key), emptySet)); 
+4
source

Source: https://habr.com/ru/post/1242116/


All Articles