我的设置活动使我的应用程序崩溃(使用共享首选项)

toe95027  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(339)

我正在开发我的第一个应用程序(如果我犯了一个愚蠢的错误,请原谅我,我对编码还比较陌生)。我为我的应用程序创建了一个设置活动,但当我从操作栏中单击设置按钮时,我的应用程序崩溃了。我试着调试这个应用程序,结果发现,当我删除了设置开关处于选中状态的行时,它工作正常,但是如果我从内存中删除应用程序并再次打开它,设置就不会保存,开关就不会打开。请帮忙。

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();

    }

}

}

q5lcpyga

q5lcpyga1#

你没有使用 findViewById 要在使用开关之前检索oncreate中的开关,使其为空:

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);

应该是:

switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);

switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications);

相关问题