我知道这个问题已经有很多答案,但我还没有找到我的问题的答案。
这是我的代码:
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.PHONE_SHARED_PREF, phoneNo);
Log.d("debug", "config "+Config.PHONE_SHARED_PREF);
Log.d("debug", "config "+phoneNo);
//Saving values to editor
editor.apply();
editor.commit();
我的理解是,editor.putString(Config.PHONE_SHARED_PREF,phoneNo)
表示将phoneNo
的值保存到PHONE_SHARED_PREF
中。如果我错了,请纠正我。
但是在日志中,Config.PHONE_SHARED_PREF
打印了默认值,而不是在 phoneNo
中分配的新值。这意味着 phoneNo
的值未正确保存,不是吗?
有人可以向我解释一下我的代码有什么问题吗? :/
最佳答案
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true)
.putString(Config.PHONE_SHARED_PREF, phoneNo)
.commit(); // returns true if successfully saved.
Log.d("debug", "config " + sharedPreferences.getString(Config.PHONE_SHARED_PREF, "");
尝试上面的方法。
关于java - commit() 后 SharedPreference 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39931055/