Android:字符串集首选项不是持久的

Bhi*_*fer 3 string android preferences

我有存储字符串集首选项的问题.我有这些实用方法用于存储:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用这些方法向后兼容GB.但我有一个问题,使用putStringSet方法不是持久的API>姜饼.应用正在运行时它是持久的.但重启后它消失了.我将描述这些步骤:

  1. 清洁安装应用程序 - 没有键X的首选项
  2. 我用字符串X存储字符串集A - 首选项包含A.
  3. 我用字符串X存储字符串集B - 首选项包含B.
  4. 关闭应用程序
  5. 重新启动应用程序 - 首选项包含A.
  6. 我用字符串X存储字符串集C - 首选项包含C.
  7. 关闭应用程序
  8. 重新启动应用程序 - 首选项包含A.

所以只有第一个值是持久的,我无法覆盖它.

其他说明:

  1. 这个方法只是替换了putStringSet和getStringSet.所以我使用commit()...但在其他地方(见下面的例子).
  2. 我试图用apply()替换commit() - 没有成功
  3. 当我在较新的API中使用旧API的代码时(我在两种方法中评论了前4行),它可以完美地工作,但效率不高

使用示例:

Editor e = mPref.edit();
PreferencesUtils.putStringSet(mPref, e, GlobalPreferences.INCLUDED_DIRECTORIES, dirs);
e.commit();
Run Code Online (Sandbox Code Playgroud)

非常感谢你的帮助.

Mr_*_*s_D 5

这有一个荒谬的重复数量 - 我打赌你这样做:

set = prefs.getStringSet("X", new HashSet<String>());
set.add("yada yada");
prefs.putStringSet("X", set);
Run Code Online (Sandbox Code Playgroud)

简而言之,android看到了那个集合,里面的那个引用同一个集合并且什么都不做.正确吗?

请参阅:尝试使用SharedPreferences存储字符串集时出现错误行为