user2313423 user2313423 - 7 months ago 55
Android Question

Android SharedPreferences String Set - some items are removed after app restart

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?

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) {
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
ed.putStringSet(CoreSetup.KEY_FEEDBACK, feedbackSet);

public Set<String> getFeedbacksSet(){
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?


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.

Update:, java.util.Set)

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

This is exactly what you are doing