有很多与共享偏好和替代方案相关的问题。 我的问题:当我关闭设备或终止应用程序时,共享首选项会丢失。 请注意,我的代码实际上适用于 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 平板电脑上丢失。
我也试过 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 - 关闭设备或终止应用程序后共享首选项丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9803838/