title: How do I show a toast when my check box is checked or unchecked?
body: <p>I want to show a toast every time the checkbox is checked or unchecked. The code below that isn't commented out runs but the toast doesn't appear. The code that is commented out runs but the app force closes with the following logcat:</p>
  
  <pre><code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
  </code></pre>
  
  <p>Here is my code:</p>
  
  <pre><code>import androidx.appcompat.app.AppCompatActivity;
  import android.os.Bundle;
  import android.widget.CheckBox;
  import android.widget.CompoundButton;
  import android.widget.Toast;
  
  public class MainActivity extends AppCompatActivity {
  
      CheckBox checkBoxOne;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          checkBoxOne = findViewById(R.id.checkBoxOne);
          if (checkBoxOne.isChecked()) {
              Toast.makeText(this, "Yes", Toast.LENGTH_SHORT).show();
          }
  /*
          checkBoxOne.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  Toast.makeText(MainActivity.this, "Hello pal", Toast.LENGTH_SHORT).show();
              }
          });
  */
      }
  }
  
  </code></pre>
  
  <p>.xml file:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity"&gt;
  
      &lt;CheckBox
          android:id="@+id/checkBoxOne"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginStart="16dp"
          android:layout_marginTop="24dp"
          android:text="CheckBox"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintTop_toTopOf="parent" /&gt;
  &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
  </code></pre>