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.


#4

I FOUND THE ISSUES !
The Solution is Wierd yet solves the " Force Stop" when pressing the certian button

CODE WITH ERROR:

public class RegistrationActivity extends AppCompatActivity {

private EditText userName, userPassword, userEmail;
private Button btn_signup1;
private TextView userLogin;
private FirebaseAuth mAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);

//UI VIEW Updater

userEmail = findViewById(R.id.userEmail);
userName = findViewById(R.id.userName);
userPassword = findViewById(R.id.userPassword);
btn_signup1 = (Button) findViewById(R.id.btn_signup1);
userLogin = findViewById(R.id.userlogin);

CODE WITHOUT ERROR :

public class RegistrationActivity extends AppCompatActivity {

private EditText userName, userPassword, userEmail;
private TextView userLogin;
private FirebaseAuth mAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);

//UI VIEW Updater

userEmail = findViewById(R.id.userEmail);
userName = findViewById(R.id.userName);
userPassword = findViewById(R.id.userPassword);
Button btn_signup1 = (Button) findViewById(R.id.btn_signup1);
userLogin = findViewById(R.id.userlogin);