Answer the question
In order to leave comments, you need to log in
What is the problem with my switch?
i'm trying to make a settings dialog but i can't save the switch correctly. When you try to save it, the application crashes. error occurs when opening dialog: Attempt to invoke virtual method "boolean android.widget.Switch.isChecked()" on a null object reference
//диалог
load();
AlertDialog.Builder builder = new AlertDialog.Builder(GameScreen.this);
RelativeLayout setting_screen = (RelativeLayout) getLayoutInflater().inflate(R.layout.setting, null);
builder.setView(setting_screen);
dialog = builder.create();
sw4 = dialog.findViewById(R.id.music);
dialog.show();
//работа свитча
public void onof(View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
ost = MediaPlayer.create(this, R.raw.ost);
ost.start();
} else {
ost.stop();
}
}
//метод сохранения и загрузки состояния приложения
public void save(){
SharedPreferences.Editor edit = saver.edit();
edit.putInt(APP_STATE, Integer.valueOf(score.getText().toString()));
edit.putBoolean(APP_MUSIC,sw4.isChecked());
edit.commit();
edit.apply();
}
public void load(){
count = saver.getInt(APP_STATE,0);
// sw4.setChecked(saver.getBoolean(APP_MUSIC, true));
if(saver.getBoolean(APP_MUSIC,true)){
ost.start();
}
else{
ost.stop();
}
}
Answer the question
In order to leave comments, you need to log in
Attempt to invoke virtual method "boolean android.widget.Switch.isChecked()" on a null object reference
isChecked()
on an object that is edit.putBoolean(APP_MUSIC,sw4.isChecked());
sw4 = dialog.findViewById(R.id.music);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question