Pages

Sunday, August 25, 2013

Android Bug: StringSet in SharedPreferences

I've been using SharedPreferences a lot last week and  I think I've noticed a bug in the Android platform.

I had to update a Set<String> in my SharedPreferences and there seems to be an error when I tried to remove a String out of the Set<String>

Set<String> set = prefs.getStringSet("set", new HashSet<String>());
set.add("one");
set.add("two");
set.add("three");
editor.putStringSet("set", set);
editor.commit();
showSet(prefs.getStringSet("set", new HashSet<String>()));

This shows the three elements correctly.
After restarting the application, the Set is correctly stored in SharedPreferences.
But then I ran this code:
Set<String> set = prefs.getStringSet("set", new HashSet<String>());
set.remove("three");
editor.putStringSet("set", set);
editor.commit();
showSet(prefs.getStringSet("set", new HashSet<String>()));

At first this seems to work fine as well. It shows the elements "one" and "two".
The strange thing happens when I now stop the application from running, and restart it.
Now when I want to get the Set<String> out of the SharedPreferences, it has all three elements again.
"one", "two" and "three". Although I removed it...

Note: if you have this error, you can make your code work by first removing the Set<String>, commiting it, and then putting it in the SharedPreferences again

You can download a sample project on this here