App throws a NullPointerException for setOnClickListener


#1

Could someone suggest a cause of the NullPointerException I get when running the app (running on a Nexus 5X)? The error seems related to setOnClickListener. I’m running the app for the first time after getting to page 25.

Error in Android Studio console

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.lentzos.nic.geoquiz, PID: 20071
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lentzos.nic.geoquiz/com.lentzos.nic.geoquiz.QuizActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference
at com.lentzos.nic.geoquiz.QuizActivity.onCreate(QuizActivity.java:19)

QuizActivity.java line 19 starts:

mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

            Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show();

        }
    });

#2

Make sure that you get a reference to the “TRUE” button
mTrueButton = (Button) findViewById(R.id.true_button);
Then set a View.OnClickListener


#3

Is that ID true_button referenced in the XML under its component? else do add it.