2

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();

                }
  • Add the whole crash logs . – ADM Mar 26 '18 at 15:07
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – ADM Mar 26 '18 at 15:08

1 Answers1

0

You are getting a NullPointerException, probably on line

String s1 = items.getText().toString();

What's happening is that if no radio button is checked you display the toast but then statements after if block are also executed and when you get checked radio button it gives null on which you end up calling getText() on giving NullPointerException. So put everything after if in else block.