dimanche 9 juillet 2017

Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference

The application works fine until I have to open the settings menu, then I get this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference

Here's the code for the Settings Activity class

        @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();

    mPrefs = getSharedPreferences("Note to self", MODE_PRIVATE);
    mEditor = mPrefs.edit();

    mSound = mPrefs.getBoolean("sound", true);

    CheckBox checkBoxSound = (CheckBox) findViewById(R.id.checkBoxSound);

    if (mSound) {
        checkBoxSound.setChecked(true);
    }
    else {
        checkBoxSound.setChecked(false);
    }

    checkBoxSound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Log.i("sound = ", "" + mSound);
            Log.i("isChecked = ", "" + isChecked);

            //If mSound is true make it false
            //If mSound is false make it true
            mSound = !mSound;
            mEditor.putBoolean("sound", mSound);
        }
    });

And here is the xml entry for the settings page:

        <CheckBox
    android:id="@+id/checkBoxSound"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/textView2"
    android:checked="false"
    android:text="@string/sound_checkbox" />

If you can tell me where to look for my answer, I would greatly appreciate it. And if you need further information don't hesitate to ask.




Aucun commentaire:

Enregistrer un commentaire