I am trying to resolve an issue in my Android Quiz app. When I do not chose an option in my RadioGroup, my app crashes: java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
This is a part of my Java code:
select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((capital.getCheckedRadioButtonId() == -1))
{
Toast.makeText(getApplicationContext(), "Select an Answer Please", Toast.LENGTH_LONG).show();
}
int selectid1 = capital.getCheckedRadioButtonId();
items = (RadioButton) findViewById(selectid1);
String s1 = items.getText().toString();
userAnswer1 = (RadioButton) findViewById(R.id.bucharest);
String theAnswer1 = userAnswer1.getText().toString();
if (s1.equals(theAnswer1)) {
score = score + 1;
}
Toast.makeText(MainActivity.this, "Your score is: " + score + " out of 6!", Toast.LENGTH_SHORT).show();
score = 0;
}
});
}
}
I also tried:
RadioButton bucharest;
RadioButton budapest;
RadioButton paris;
bucharest = (RadioButton) findViewById(R.id.bucharest);
budapest = (RadioButton) findViewById(R.id.budapest);
paris = (RadioButton) findViewById(R.id.paris);
if (bucharest.isChecked() || budapest.isChecked() || paris.isChecked()) {
Toast.makeText(MainActivity.this, "chosen", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Please select option", Toast.LENGTH_SHORT).show();
}