[英]My settings activity makes my app crash (using shared preferences)
I am working on my first app (so please forgive me if I've made a silly mistake, I am relatively new to coding).我正在开发我的第一个应用程序(如果我犯了一个愚蠢的错误,请原谅我,我对编码比较陌生)。 I created a settings activity for my app, but the moment I click on the settings button from the action bar, my app crashes.
我为我的应用程序创建了一个设置活动,但是当我单击操作栏中的设置按钮时,我的应用程序崩溃了。 I tried debugging the app, turns out the moment I remove the lines where I keep the switches on setchecked, it works fine, but then if I remove the app from memory and open it again, the setting isnt saved, the switches aren't on.
我尝试调试该应用程序,结果是当我删除我保持设置检查开关的行时,它工作正常,但是如果我从 memory 删除应用程序并再次打开它,设置没有保存,开关没有上。 Please help.
请帮忙。
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Switch;
public class SettingsActivity extends AppCompatActivity {
public static final String SETTINGS_PREFERENCES = "com.example.taskmasterv3.SettingsPreferences";
Switch switchReminder, switchNotifications;
boolean reminders;
boolean notifications;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
SharedPreferences prefs = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE);
reminders = prefs.getBoolean("reminders", false);
notifications = prefs.getBoolean("notifications", false);
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications);
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
if (switchReminder.isChecked()) {
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.commit();
}
if (switchNotifications.isChecked()) {
notifications = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("notifications", notifications);
editor.commit();
}
}
}
You're not using findViewById
to retrieve your switches in onCreate before you're using them, so they're null:在使用它们之前,您没有使用
findViewById
来检索 onCreate 中的开关,因此它们是 null:
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications); <-- wrong order
switchReminder = findViewById(R.id.switchReminder); <-- too late, already tried to use it above
switchNotifications = findViewById(R.id.switchNotifications);
it should be:它应该是:
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.