I have a problem with storing string set preference. I have these utility methods for storing:
public static void putStringSet(SharedPreferences pref, Editor e, String key, Set<String> set)
{
if (Utils.isApiLevelGreaterThanGingerbread())
{
// e.remove(key); // I tried to remove it here
e.putStringSet(key, set);
}
else
{
// removes old occurences of key
for (String k : pref.getAll().keySet())
{
if (k.startsWith(key))
{
e.remove(k);
}
}
int i = 0;
for (String value : set)
{
e.putString(key + i++, value);
}
}
}
public static Set<String> getStringSet(SharedPreferences pref, String key, Set<String> defaultValue)
{
if (Utils.isApiLevelGreaterThanGingerbread())
{
return pref.getStringSet(key, defaultValue);
}
else
{
Set<String> set = new HashSet<String>();
int i = 0;
Set<String> keySet = pref.getAll().keySet();
while (keySet.contains(key + i))
{
set.add(pref.getString(key + i, ""));
i++;
}
if (set.isEmpty())
{
return defaultValue;
}
else
{
return set;
}
}
}
I use these methods to be backward compatible with GB. But I have a problem that using putStringSet method isn't persistent for API > gingerbread. It is persistent while app is runing. But it dissapears after restart. I will describe the steps:
- Clean install of application - there is no preference with key X
- I store string set A with key X - preference contains A
- I store string set B with key X - preference contains B
- Close app
- Restart of app - preference contains A
- I store string set C with key X - preference contains C
- Close app
- Restart of app - preference contains A
So only the first value is persistent and I cannot overwrite it.
Other notes:
- this methods just replaces putStringSet and getStringSet. So I use commit()...but elsewhere (see example below).
- I tried to replace commit() with apply() - no success
- When I use code for older APIs in newer APIs (I commented first 4 lines in both methods) it works flawlessly but it isn't so efficient
Example of use:
Editor e = mPref.edit();
PreferencesUtils.putStringSet(mPref, e, GlobalPreferences.INCLUDED_DIRECTORIES, dirs);
e.commit();
Thnak you very much for help.