我曾经使用过很多次共享优惠,但出于某种原因,我测试的一个新应用程序并没有保存更改。这里是重要代码的片断:
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
widgets.add(name + " " + Integer.toString(appWidgetId) + " " + address);
sp.edit().putStringSet(getString(R.string.key_widgets), widgets).commit();
我曾经用日志来检查部件是否添加到集中, 但更新后的集从未保存。 如果我将最后一行更改为...
sp.edit().putStringSet(getString(R.string.key_widgets), widgets).putString("testkey", "testvalue").commit();
一切都会好起来的 我错过了什么?
* 过时:
我发现这也有效:
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
Set<String> newWidgets = new HashSet<String>();
for (String widget : widgets) newWidgets.add(widget);
newWidgets.add(name + " " + Integer.toString(appWidgetId) + " " + address);
sp.edit().putStringSet(getString(R.string.key_widgets), newWidgets).commit();
也许我在文档中遗漏了 需要为编辑 创建一个新对象来保存预设文件的内容。
* 日期:
如果我创建一个编辑器对象,这没有什么区别:
SharePreferences.Editor spe = sp.edit();
spe.putStringSet(getString(R.string.key_widgets), widgets)
spe.commit();