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

有很多问题与共享偏好和替代方案有关.
我的问题:当我关闭设备或杀死应用程序时,共享首选项会丢失.
请注意,我的代码实际上是在使用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;
}

通过调用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();
}

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

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

谢谢你的帮助,
克里斯

解决方法:

我已经找到了一个可以在我的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();
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...