共享preferences关闭装置或杀死该应用程序后迷路 [英] Shared Preferences get lost after shutting down device or killing the app

查看:174
本文介绍了共享preferences关闭装置或杀死该应用程序后迷路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多问题在那里与共享preferences和替代品。 我的问题:当我关闭设备或杀死应用程序,共享preferences迷路。 请注意,我的code实际上正在宏碁A500。但在我的摩托罗拉Xoom MZ604它不工作!

there are lots of questions out there related to shared preferences and the alternatives. My problem: when I shut down the device or kill the app, the shared preferences get lost. Please note that my code actually is working on Acer A500. But on my Motorola Xoom MZ604 it isn't working!!

首先,我试图恢复我在的onCreate HashSet的。这种方法被称为是肯定的,并在单件实现。

First of all I try to restore my HashSet in onCreate. This method is called for sure and is implemented in a singleton.

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。尽管它没有给出,这个方法被称为是肯定的,在preferences迷失在任何情况下,我都试图挽救它的onPause具有相同的结果。

By calling onDestroy I save the HashSet. Even though it isn't given, that this method is called for sure, the Preferences get lost in any case, I have trying to save it in onPause with the same result.

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

有没有人有问题,共享preferences和XOOM设备,也还是我唯一一个?也许了什么事与我的code,但数据不会丢失在我的宏碁平板电脑。

Has had anyone problems with Shared Preferences and the XOOM device,too or am I the only one? Perhaps something is fishy with my code but the data doesn't get lost on my Acer Tablet.

我也试着preferenceManager.getDefaultShared preferences(上下文)获得的共享preferences对象

I've also tried PreferenceManager.getDefaultSharedPreferences(context) to get object of SharedPreferences

感谢您的帮助, 克里斯

Thanks for your help, Chris

推荐答案

我已经想通了一个解决方案,它是双向,对我的宏基和我的XOOM设备上:你有新的承诺之前调用clear()的编辑器数据:

I've figured out a solution that works both, on my Acer and on my XOOM device: you have to call clear() on the editor before committing new data:

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

这篇关于共享preferences关闭装置或杀死该应用程序后迷路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆