最佳答案
I'm trying to store a set of strings using the SharedPreferences API.
Set<String> stringSet = sharedPrefs.getStringSet("key", new HashSet<String>());
stringSet.add(new_element);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putStringSet(stringSet);
editor.commit()
The first time I execute the code above, stringSet
is set to the default value (the just created and empty HashSet
) and it is stored without problems.
The second and subsequent times I execute this code, a stringSet
object is returned with the first element added. I can add the element and, during the program execution, it is apparently stored in the SharedPreferences
. However, when the program is killed and the SharedPreferences
is loaded again from persistent storage, the newer values are lost.
How can the second and subsequent elements be stored so that they don't get lost?