我的 Storyteller
类与共享播放。
它使用包含22个字符串的默认值加载stringset,保存在其chapters
变量中。
当程序稍后发生"完整"事件时,Storyteller
将从chapters
中删除字符串,然后将其提交为共享Preferences。
我的日志显示了22个字符串,然后删除并承诺为编辑器后21个字符串。
。当我再次运行程序时,加载了22章而不是预期的21。
private Set<String> chapters;
protected Storyteller(Context c) {
buffer = "";
choices = new JSONArray();
SharedPreferences sharedPref = c.getSharedPreferences(c.getString(R.string.pref_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
chapters = sharedPref.getStringSet("chapters", new HashSet<String>());
Log.v("sip", chapters.toString());
Log.v("sip-loaded", String.valueOf(chapters.size()));
if (chapters.isEmpty()) {
Log.v("sip", "saving vignettes");
ArrayList<String> names = vignettes();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
chapters.add(name);
}
editor.putStringSet(c.getString(R.string.chapters), chapters);
editor.commit();
}
Log.v("sip", String.valueOf(chapters.size()));
}
public void complete(String chapter, Context c) {
chapters.remove(chapter);
SharedPreferences sharedPref = c.getSharedPreferences(c.getString(R.string.pref_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet(c.getString(R.string.chapters), chapters);
editor.commit();
Log.v("sip", String.valueOf(chapters.size()));
chapters = sharedPref.getStringSet("chapters", new HashSet<String>());
Log.v("sip", String.valueOf(chapters.size()));
}
第一次运行的登录:
12-10 15:24:27.161 3241-3241/? V/sip-loaded: 22
12-10 15:24:27.161 3241-3241/? V/sip: 22
12-10 15:24:27.161 3241-3241/? V/sip-storyloaded: Story loaded
12-10 15:24:37.409 3241-3241/coffeechoices.quantumproductions.com.choicescoffee V/sip: 21
12-10 15:24:37.409 3241-3241/coffeechoices.quantumproductions.com.choicescoffee V/sip: 21
12-10 15:24:37.409
第二次运行的登录:
12-10 15:25:34.097 3307-3307/coffeechoices.quantumproductions.com.choicescoffee V/sip-loaded: 22
12-10 15:25:34.097 3307-3307/coffeechoices.quantumproductions.com.choicescoffee V/sip: 22
12-10 15:25:34.098 3307-3307/coffeechoices.quantumproductions.com.choicescoffee V/sip-storyloaded: Story loaded
编辑:
getTring(r.string.chapters)是 chapters
,请参阅字符串文件:
<resources>
<string name="app_name">choices.coffee</string>
<string name="pref_key">choices.coffee</string>
<string name="chapters">chapters</string>
</resources>
我正在尝试使用"章节"和Getstring,同样的结果。
请注意,保存在complete
函数中后,我可以从文件中读取,它显示正确的金额,21。重新启动时,是22设置为空)未被调用。
您使用的是两个不同的键: R.string.chapters
和 "chapters"
。
我假设它们不等于同一字符串。也只使用一个键值切换。
编辑:
您绝不应该根据sharedPreferences.getStringset()的文档直接更改chapters
:
请注意,您不得修改此调用返回的设置实例。如果您这样做,则无法保证存储数据的一致性,也无法完全修改实例。
呼叫.clear()
SharedPreferences sharedPref = c.getSharedPreferences(c.getString(R.string.pref_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
允许它正确保存。