【发布时间】:2012-04-05 22:13:02
【问题描述】:
有很多与共享偏好和替代方案相关的问题。 我的问题:当我关闭设备或终止应用程序时,共享首选项会丢失。 请注意,我的代码实际上是在 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。即使没有给出,肯定会调用此方法,但无论如何 Preferences 都会丢失,我试图将其保存在 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();
}
Shared Preferences 和 XOOM 设备是否也遇到过任何问题,还是只有我一个?也许我的代码有问题,但数据不会在我的 Acer 平板电脑上丢失。
我也尝试过 PreferenceManager.getDefaultSharedPreferences(context) 来获取 SharedPreferences 的对象
感谢您的帮助, 克里斯
【问题讨论】:
-
你检查
commit的返回值了吗? -
好点 - 但不幸的是:真的...
-
我从未在任何设备上见过这种情况,而且我见过很多(虽然不是平板电脑,只是手机)。既然您自己提到它只发生在 Xoom 上,这可能只是供应商特定的问题吗?
-
你写过空键吗?请参阅:stackoverflow.com/questions/5368442/…
-
事实证明这也可能是由无效的首选项键引起的,例如包含换行符的键:stackoverflow.com/questions/28385132/…