我遇到了存储字符串集合偏好的问题。我有以下用于存储的实用方法:
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向后兼容。但是我遇到了一个问题,即在API > gingerbread中使用putStringSet方法不是持久性的。它只在应用程序运行时是持久性的,但在重新启动后就会消失。我将描述以下步骤:
- 干净地安装应用程序-没有带有X键的首选项
- 我使用键为X的字符串集A-首选项包含A
- 我使用键为X的字符串集B-首选项包含B
- 关闭应用程序
- 重新启动应用程序-首选项包含A
- 我使用键为X的字符串集C-首选项包含C
- 关闭应用程序
- 重新启动应用程序-首选项包含A
其他注意事项:
- 这些方法只是替换了putStringSet和getStringSet。因此,我使用commit()……但在其他地方(见下面的示例)。
- 我尝试将commit()替换为apply()——但没有成功
- 当我在较新的API中使用旧API的代码时(我在两种方法中都注释了前4行),它可以完美地工作,但效率不高
Editor e = mPref.edit();
PreferencesUtils.putStringSet(mPref, e, GlobalPreferences.INCLUDED_DIRECTORIES, dirs);
e.commit();
非常感谢您的帮助。