检索共享首选项值 returns null

Retrieving a shared preference value returns null

我正在使用共享首选项将字符串值存储在一个 activity 中,但是当尝试在其他 activity 中检索字符串时,它 return 为空。

下面是我的代码:

Activity答:

SharedPreferences preferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);

SharedPreferences.Editor = preferences.edit();

editor.putString("FirstUserName", strUserName);
editor.commit();

以上代码表明我正在将字符串值保存在共享首选项中。

现在,

Activity乙:

SharedPreferences preferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);

String strUserName = preferences.getString("FirstUserName", null);

以上代码preferences.getString("FirstUserName", null)return无效。

我不知道问题出在哪里,我想我已经正确地编写了代码。

代码如有错误,请回复

提前致谢。

试试这个...

-> 存储价值:

SharedPreferences sharedPreferences = getSharedPreferences( "MyPref", 0);

SharedPreferences.Editor编辑器=sharedPreferences.edit(); editor.putString("firstUserName","user_name");

editor.commit(); editor.apply();

-> 检索值:

SharedPreferences sharedPreferences = getSharedPreferences( "MyPref", 0);

Log.e("FirstName", sharedPreferences.getString("firstUserName","");

In your second Activity you write "MyPrefs", and in the firts Activity you write "MyPref" without "s".

你的变化 SecondActivity.java

SharedPreferences preferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);

在 Activity A 中你得到 "MyPref",但在 Activity B "MyPrefs" 中有额外的 's'。这将获得另一个 sharedpreferences 实例,这就是您获得空值的原因。我建议您在常量 class.

中声明这些类型的字符串