【发布时间】:2014-11-19 18:40:38
【问题描述】:
我正在使用 sharedPref 在活动之间传递一个字符串。 我正在努力使我的代码更有效,但我遇到了一个我无法弄清楚的奇怪问题。
我在 MainActivity.class 中的代码:
@覆盖 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
//if statement for the first run of the app, else statement uses the defined city.
if (SharedPref.getCity().equals("")) {
} else {
cityText = (TextView) findViewById(R.id.prefCity);
cityText.setText(SharedPref.getCity());
}
我的 SharedPref.java :
public class SharedPref {
private static SharedPreferences mSharedPreferences;
//sharedPref Manager.
public SharedPref(final Context context) {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public static void setCity(String item) {
mSharedPreferences.edit().putString("city", item).apply();
}
public static String getCity() {
return mSharedPreferences.getString("city", "");
}
}
如您所见,在我的 MainActivity.class 中,我通过“SharedPref.getCity()”访问数据。 直接来自类的意思,这就是我使用静态方法的原因。 但是应用程序崩溃了。 奇怪的是,如果我像这样在 MainActivity 中初始化我的 sharedpref:
SharedPref sharedPref = new SharedPref(getBaseContext());
那么应用程序就可以正常工作,即使 sharedPref 是一个甚至不会使用一次的变量!
我错过了什么?
ps 这是我的 logcat 图片:
提前感谢您的帮助。
【问题讨论】:
-
我认为因为 SharedPref.getCity() 返回 null,尝试将“if (SharedPref.getCity().equals(""))”更改为“if (SharedPref .getCity()== null )"
-
您使用 sharedPrefs 而不是意图传递的任何特殊原因?
标签: java android sharedpreferences