Android: String set preference is not persistent

前端 未结 2 430
忘掉有多难
忘掉有多难 2020-12-11 09:00

I have a problem with storing string set preference. I have these utility methods for storing:

public static void putStringSet(SharedPreferences pref, Editor         


        
相关标签:
2条回答
  • 2020-12-11 09:29

    This has a ridiculous amount of duplicates - I bet that you do :

    set = prefs.getStringSet("X", new HashSet<String>());
    set.add("yada yada");
    prefs.putStringSet("X", set);
    

    In short android sees that set and the one inside refer to the same set and does nothing. Correct ?

    See: Misbehavior when trying to store a string set using SharedPreferences

    0 讨论(0)
  • 2020-12-11 09:35

    My condition is very similar to yours, the only difference is when restart the app, preference contains A, B, C, but when reinstall it or reboot the phone, B&C are gone.

    I also tried replace commit() with apply(), as this post adviced SharedPreferences not persistent , but still not to work.

    I solved this problem by remove & commit the preference before replacing it:

    editor.remove("StringSetKey");
    editor.commit();
    
    editor.putStringSet("StringSetKey", newSet);
    editor.commit();
    

    Ps: you can type adb pull /data/data/<packagename>/shared_prefs/xxxx.xml in cmd line to see if the commit() really works

    Pps: I think this is a bug with putStringSet....

    hope this will help you ;)

    0 讨论(0)
提交回复
热议问题