gpt4 book ai didi

java - Button OnClick 中 SharedPreferences 的 NullPointerException

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

我正在尝试更新关于用户是否选中不再显示欢迎屏幕的框的共享首选项。我通过一个按钮访问我的共享首选项我的 onClick 监听器。我遇到空指针异常,但我不知道如何修复它?

这是我的代码....

public class WelcomeScreenActivity extends Activity {


SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.welcomescreen);


final Button button = (Button) findViewById(R.id.welcomecontinue);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) findViewById(R.id.welcomecheckbox);
if(cb.isChecked()){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
Intent intent = new Intent(WelcomeScreenActivity.this, MainActivity.class);
startActivity(intent);
} else if(!cb.isChecked()){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, false);
editor.commit(); // Very important to save the preference
Intent intent = new Intent(WelcomeScreenActivity.this, MainActivity.class);
startActivity(intent);
}
}
});


}

}

任何人都可以阐明这一点吗?

最佳答案

SharedPreferences mPrefs;

你从未初始化过它。虽然你正在使用它

mPrefs.edit();

做这样的事情:

SharedPreferences mPrefs = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);

使用前

关于java - Button OnClick 中 SharedPreferences 的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20752799/

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