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