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