gpt4 book ai didi

Android在哪里声明SharedPreferences

转载 作者:行者123 更新时间:2023-11-29 17:53:25 25 4
gpt4 key购买 nike

我试图在我的第二个 Activity 中使用 edittexts 来更改我的第一个/主要 Activity 中的字符串。因此,要做到这一点,必须使用 SharedPreferences。

在我的第二个 Activity 的顶部,我宣布了他们和一个编辑器。它会导致 nullpointexception 错误并使代码崩溃。我不确定在哪里初始化它,因为我希望在主要/第一个 Activity 中查看 sharedPreferences。

SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();

此外,将这段代码放入 sharedprefs 字典是否合适?

if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
{
editor.putString("intro", introstring);
}

最佳答案

At the top of my second activity

您的意思是作为字段 - 是的,这将导致 NPE,原因在 Why getApplicationContext() in constructor of Activity throws null pointer exception? 中解释。

所以按照评论中的建议,你需要

class YourSecondActivity extends Activity {

SharedPreferences sp;
Editor e;

protected void onCreate() {
sp = PreferenceManager.getDefaultSharedPreferences(this); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
}

meth() {
//...
if(!introstring.isEmpty()) { // save the fields if NOT empty
e.putString("intro", introstring);
e.commit(); // you forgot to commit
}
}
}

关于Android在哪里声明SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21345306/

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