gpt4 book ai didi

java - SharedPref 中的静态方法导致我的应用程序崩溃

转载 作者:行者123 更新时间:2023-12-01 12:15:41 26 4
gpt4 key购买 nike

我正在使用sharedPref 在 Activity 之间传递一个字符串。我正在努力使我的代码更有效,但我遇到了一个我无法解决的奇怪问题。

我在 MainActivity.class 中的代码:

@Override 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 = new SharedPref(getBaseContext());

然后应用程序就可以正常工作,即使sharedPref是一个甚至没有使用过一次的变量!

我错过了什么?

p.s 这是我的 logcat 图片: logcat

预先感谢您的帮助。

最佳答案

最初共享首选项甚至不包含 var“city”,因此最初条件应该是 sharepref.contains(“city”),然后在进一步迭代中检查它的值。

关于java - SharedPref 中的静态方法导致我的应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com