Android SharedPreferences not saving

android, sharedpreferences

Solution

We just need to read the documentation more carefully

According to getStringSet

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

In fact it should have been noted in SharedPreferences.Editor not to send putStringSet a set that may modified afterwards. Make a copy of the set returned from getStringSet before modifying, and make a copy of your set before sending it to putStringSet.

SharedPreferences myPrefs = getSharedPreferences(myPrefName, MODE_PRIVATE);
HashSet<String> mySet = new HashSet<string>(myPrefs.getStringSet(mySetKey, new HashSet<string()));
....
SharedPreferences.Editor myEditor = myPrefs.edit();

Then one of

myEditor.putStringSet(mySetKey, new HashSet<String>(mySet));

or

myEditor.putStringSet(mySetKey, (Set<String>) mySet.clone());

Problem

I've used shared preferences many times, but for some reason, changes aren't being saved in a new app that I'm testing. Here's a snippet of the important code: ``` SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE); Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>())); widgets.add(name + " " + Integer.toString(appWidgetId) + " " + address); sp.edit().putStringSet(getString(R.string.key_widgets), widgets).commit(); ``` I've used logging to check that the widget is added to the set, but the updated set is never saved. If I change the last line to... ``` sp.edit().putStringSet(getString(R.string.key_widgets), widgets).putString("testkey", "testvalue").commit(); ``` ...then everything saves just fine. What am I missing? *UPDATE: I found out that this also works: ``` SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE); Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>())); Set<String> newWidgets = new HashSet<String>(); for (String widget : widgets) newWidgets.add(widget); newWidgets.add(name + " " + Integer.toString(appWidgetId) + " " + address); sp.edit().putStringSet(getString(R.string.key_widgets), newWidgets).commit(); ``` Perhaps I missed something in the documentation about needing to create a new object for the editor to save the prefs. *UPDATE 2: It makes no difference if I create an editor object: ``` SharePreferences.Editor spe = sp.edit(); spe.putStringSet(getString(R.string.key_widgets), widgets) spe.commit(); ```

Original source

Related problems