SharedPreferences always get default value in my existing app but when created new app its ok

后端 未结 11 903
眼角桃花
眼角桃花 2020-12-16 13:18

SharedPreferences doesn\'t work correct in one existing apps. I tried many different ways but still not working. Always get default values app start again.

  • It\
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 13:45

    One thing you could try is to get a new SharedPreference instance after committing and see what happens:

    SharedPreferences pref = this.getSharedPreferences("test", MODE_PRIVATE);
    String user = pref.getString("user", default_user);
    if (user.equals(default_user)) {
        pref.edit().putString("user", "new_user").commit();
        SharedPreferences newPref = this.getSharedPreferences("test", MODE_PRIVATE);
        user = newPref.getString("user", default_user);
    }
    

    Your editor is committing a new preference map into disk, but it is possible that the old SharedPreference instance is not notified of the change.

提交回复
热议问题