Android SharedPreferences字符串集-应用重新启动后,某些项目将被删除 [英] Android SharedPreferences String Set - some items are removed after app restart
问题描述
我将其保存在共享首选项中的字符串设置(如果我没关系的话).我开始其他活动,回去再读一遍,没关系.如果我关闭该应用程序,然后重新启动,则会得到该设置,但是只有1个项目而不是4个项目.它总是发生.是否存在已知问题?我该怎么办?
I save a string set in the shared preferences, if I read it out it's ok. I start other activities, go back and read it again, it's ok. If I close the application, and start it again, I get the set, but with only 1 item instead of 4. It happens all the time. Is there a known issue? What could I do wrong?
在一个类中,在应用程序的oncreate方法中创建的内容有一个SharedPreferences和一个SharePreferences.Editor变量.我在保存和加载方法中使用它们.
In a class, what is created in the application's oncreate method I have a SharedPreferences and a SharePreferences.Editor variable. I use them in the save and load methods.
public void saveFeedback(FeedbackItem feedbackItem) {
checkSp();
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
}
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
feedbackSet.add(json.toString());
ed.putStringSet(CoreSetup.KEY_FEEDBACK, feedbackSet);
ed.commit();
}
public Set<String> getFeedbacksSet(){
checkSp();
Set<String> ret = sp.getStringSet(CoreSetup.KEY_FEEDBACK, null);
return ret;
}
private void checkSp(){
if(this.sp == null)
this.sp = applicationContext.getSharedPreferences(applicationContext.getPackageName(), Context.MODE_PRIVATE);
if(this.ed == null)
this.ed = this.sp.edit();
}
我只是不知道怎么发生,要在应用程序运行时完美地存储所有项目,然后重新启动后并不是所有项目都在集合中.而且我认为,如果删除所有项目,则比删除某些项目更容易接受,而其中一项仍然存在.有解释吗?
I just can't understand how could it happen, to store perfectly all items while the app is running, then after a restart not all items are in the set. And I think if all items are removed it could be more acceptable than some items are gone, and one item is still there. Is there an explanation?
推荐答案
根据您的问题,只有在将4个项目添加到集合中之后,才应调用commit.在您的代码中,您正在为每个反馈调用commit,这将覆盖以前的反馈.
Based on your question, you should call commit only after 4 items have been added to the set. In your code, you are calling commit for each feedback which will overwrite the previous feedback.
更新: http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet(java.lang.String ,java.util.Set)
Update: http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet(java.lang.String, java.util.Set)
请注意,您不得修改此调用返回的设置实例.如果这样做,将无法保证所存储数据的一致性,也根本无法保证修改实例的能力.
这正是你在做什么
这篇关于Android SharedPreferences字符串集-应用重新启动后,某些项目将被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!