2013-05-29 14 views
3

我在存储字符串集偏好时遇到了问题。我有这些实用的方法来存储:Android:字符串集偏好不是持久的

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>姜饼不是持久的。它在应用程序运行时保持不变。但重启后消失。我将介绍的步骤:

  1. 干净安装应用程序的 - 没有与主要X没有偏好
  2. 我存储的字符串集合A与关键X - 偏好包含
  3. 我存储串集B与键X - 优选含有B
  4. 关闭应用
  5. 应用的重启 - 偏好包含
  6. 我串集合C存储与密钥X - 优选含有C
  7. 氯OSE应用
  8. 应用程序的重新启动 - 偏好包含

所以只有第一个值是持久的,我不能覆盖它。

其他说明:

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

例子:

Editor e = mPref.edit(); 
PreferencesUtils.putStringSet(mPref, e, GlobalPreferences.INCLUDED_DIRECTORIES, dirs); 
e.commit(); 

Thnak你非常的帮助。

+0

您如何初始化dirs? –

+0

[尝试存储使用SharedPreferences的字符串集时出现错误行为]的可能重复(http://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-sharedpreferences) –

回答

1

我的条件与您的条件非常相似,唯一的区别是重新启动应用程序时,首选项包含A,B,C,但重新安装或重新启动手机时,B & C已不存在。

我也试着用apply()替换commit(),因为这篇文章提示SharedPreferences not persistent,但是还是不行。

我解决了删除&这个问题提交喜好更换前:

editor.remove("StringSetKey"); 
editor.commit(); 

editor.putStringSet("StringSetKey", newSet); 
editor.commit(); 

PS:你可以在CMD行中键入adb pull /data/data/<packagename>/shared_prefs/xxxx.xml,看是否提交()真的有用

PPS:我认为这是一个错误与putStringSet ....

希望这会帮助你;)

+0

我给你一个-1,因为你所要做的只是阅读[javadoc for getStringSet()](http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet%28java.lang.String ,%20java.util.Set%3Cjava.lang.String%3E%29):_注意你不能修改这个调用返回的set实例。如果存储数据的一致性不能得到保证,也不能保证你可以修改实例。当你遇到问题时,解决方案不是黑客,而是理解发生的事情。 _为什么你必须删除设置并重新添加?这是否真的对你有意义?_ –

+0

@Mr_and_Mrs_D thx提及 – zhangxaochen

+0

编辑你的答案是正确的,将撤销我的投票 –