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

前端 未结 6 2015
南笙
南笙 2021-02-03 19:38

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

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-03 20:31

    According to the document, the String Set in SharedPreferences should treated as immutable, things go south when trying to modify it. A work around would be: Get the existing set, make a copy of it, update the copy and then save it back to the shared preferences like it was a new set.

    Set feedbackSet = getFeedbacksSet();
    if(feedbackSet == null){
        feedbackSet = new HashSet();
    }
    
    //make a copy of the set, update the copy and save the copy
    Set newFeedbackSet = new HashSet();
    JSONObject json = createJSONObjectfromFeedback(feedbackItem);
    newFeedbackSet.add(json.toString());
    newFeedbackSet.addAll(feedbackSet);
    ed.putStringSet(CoreSetup.KEY_FEEDBACK, newFeedbackSet);
    ed.commit();
    

提交回复
热议问题