E
E
EnGold2022-02-05 14:24:53
Java
EnGold, 2022-02-05 14:24:53

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

1 answer(s)
O
Orkhan, 2022-02-05
@EnGold

Attempt to invoke virtual method "boolean android.widget.Switch.isChecked()" on a null object reference

Well, here , as for me , it is quite clearly written that you are trying to call a method isChecked()on an object that is
null .
edit.putBoolean(APP_MUSIC,sw4.isChecked());
sw4 = dialog.findViewById(R.id.music);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question