簡體   English   中英

我的設置活動使我的應用程序崩潰(使用共享首選項)

[英]My settings activity makes my app crash (using shared preferences)

我正在開發我的第一個應用程序(如果我犯了一個愚蠢的錯誤,請原諒我,我對編碼比較陌生)。 我為我的應用程序創建了一個設置活動,但是當我單擊操作欄中的設置按鈕時,我的應用程序崩潰了。 我嘗試調試該應用程序,結果是當我刪除我保持設置檢查開關的行時,它工作正常,但是如果我從 memory 刪除應用程序並再次打開它,設置沒有保存,開關沒有上。 請幫忙。

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

        }
    }
}

在使用它們之前,您沒有使用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);

它應該是:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM