微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐