我知道这个问题已经有吨吨的答案,但我还没有找到我的问题的答案。SharedPreference提交后未更新()
这里是我的代码:
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
。如果我错了,请纠正我。
但是,在Log中,Config.PHONE_SHARED_PREF
显示默认值,而不是在phoneNo
中分配的新值。这意味着phoneNo
的值没有正确保存,不是?
有人可以向我解释我的代码有什么问题吗? :/
'commit()'和'apply()'是相同的,后者不返回布尔值。删除并重试。您可以使用'editor.getString(Config.PHONE_SHARED_PREF,“”)''来获取值。如果密钥不存在,则返回第二个参数。 –
对不起,请尝试'sharedPreferences.getString(...)'。 –
它什么也没有返回(第二参数) – August