Set in android sharedpreferences does not save on force close

后端 未结 2 1377
梦如初夏
梦如初夏 2020-12-15 18:15

Im trying to use androids sharedpreferences, I´ve logged everything and the code below really commits the string set. The problem is when I force close the app and start aga

2条回答
  •  醉梦人生
    2020-12-15 18:56

    You can also work around the bug mentioned by g00dy this way:

    Get the set from sharedPreferences and save it in a variable.

    Then just delete the set in sharedpreferences before adding it again when saving.

    SharedPreferences.Editor editor= sharedPref.edit();
    editor.remove("mSet");
    editor.apply(); 
    editor.putStringSet("mSet", mSet);
    editor.apply();
    

    Make sure to use apply() or commit() twice.

    Alternatively, if you are working in Kotlin simply :

    PreferenceManager.getDefaultSharedPreferences(applicationContext)
        .edit {
            this.remove("mSet")
            this.apply()
            this.putStringSet("mSet", mSet)
        }
    

提交回复
热议问题