关闭设备或终止应用后,共享首选项会丢失

Chr*_*way 11 android sharedpreferences

有很多问题与共享偏好和替代方案有关.我的问题:当我关闭设备或杀死应用程序时,共享首选项会丢失.请注意,我的代码实际上是在使用Acer A500.但在我的摩托罗拉Xoom MZ604上,它无法正常工作!!

首先,我尝试在onCreate中恢复我的HashSet.这个方法是肯定调用的,并以单例形式实现.

public boolean restoreCollection(Context context){
    SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.restore_values), 0);
    if(settings.getStringSet(context.getString(R.string.collection), null) != null){
        collection = settings.getStringSet(context.getString(R.string.collection), null);
        return true;
    } 
    collection = new HashSet<String>();
    return false;
}
Run Code Online (Sandbox Code Playgroud)

通过调用onDestroy,我保存了HashSet.即使没有给出,这个方法是肯定调用的,但是在任何情况下,首选项都会丢失,我试图将它保存在onPause中,结果相同.

public void saveCollection(Context context){
    SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.restore_values), 0);
    SharedPreferences.Editor e = settings.edit();
e.putStringSet(context.getString(R.string.collection), collection);
e.commit();
}
Run Code Online (Sandbox Code Playgroud)

共享首选项和XOOM设备是否有任何问题,或者我是唯一的问题?也许我的代码有些可疑但数据不会在我的Acer Tablet上丢失.

我也尝试过PreferenceManager.getDefaultSharedPreferences(context)来获取SharedPreferences的对象

谢谢你的帮助,克里斯

Chr*_*way 14

我已经找到了一个可以在我的Acer和我的XOOM设备上运行的解决方案:在提交新数据之前,你必须在编辑器上调用clear():

public void saveCollection(Context context){
    SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.restore_values), 0);
    SharedPreferences.Editor e = settings.edit();
    e.clear();
    e.putStringSet(context.getString(R.string.collection), collection);
    e.commit();
}
Run Code Online (Sandbox Code Playgroud)

  • 这当然不是一个解决方案 - 我的意思是偏好意味着持久性 - 如果要清除首选项,大多数用例都会被取消 - 原因是其他地方 (2认同)

Jon*_*ona 13

使用带有SharedPreferences的字符串集时,我遇到了完全相同的问题.我发现了为什么会这样,以及如何解决它.

阅读SharedPreferences.getStringSet的API文档非常重要(String key,Set defValues)

基本上不要修改或触摸返回的Set!如果你这样做,你将获得SharedPreferences的奇怪结果.:)

请享用!