安卓:string设置preference不具有持续性 [英] Android: String set preference is not persistent
问题描述
我有存储字符串设定preference一个问题。我有这些工具方法,用于存储:
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;
}
}
}
我用这些方法是向后兼容GB。但我有一个问题,使用putStringSet方法不具有持续性的API>姜饼。这是持久性的,而应用程序是乳宁。但重新启动后自败。我将描述的步骤:
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:
-
适用
- 在全新安装 - 没有preference与主要X
- 在我店串集A和密钥X - preference包含
- 在我店字符串集合B用密钥X - preference含有B
- 关闭应用程序
- 的应用程序重新启动 - preference包含
- 在我店字符串集合C与密钥X - preference含有C
- 关闭应用程序
- 的应用程序重新启动 - preference包含
- 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.
其他注意事项:
- 在这种方法只是取代putStringSet和getStringSet。所以,我用的commit()...但在其他地方(见下面的例子)。
- 我试图替代提交()与应用() - 没有成功
- 当我使用code对老年人的API在新的API(我在评论这两种方法第4行),它完美的作品,但它不是那么有效
使用示例:
Editor e = mPref.edit();
PreferencesUtils.putStringSet(mPref, e, GlobalPreferences.INCLUDED_DIRECTORIES, dirs);
e.commit();
Thnak你非常的帮助。
Thnak you very much for help.
推荐答案
这有重复荒谬的量 - 我敢打赌,你做的:
This has a ridiculous amount of duplicates - I bet that you do :
set = prefs.getStringSet("X", new HashSet<String>());
set.add("yada yada");
prefs.putStringSet("X", set);
在短机器人看见该集合和所述一个内指代相同的集合和什么都不做。是否正确?
In short android sees that set and the one inside refer to the same set and does nothing. Correct ?
请参阅:<一href="http://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-shared$p$pferences/14034804#14034804">Misbehavior尝试存储字符串设定使用共享preferences
这篇关于安卓:string设置preference不具有持续性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!