0

I have two radio button in my app Yes and No.So whenever user select Yes then I want to show bottom sheet dialog but app is crashing whenever it launches.

It is showing error below:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference

Below is my code:

public class Signup extends AppCompatActivity {

RadioButton radioButton;
RadioGroup radioGroup;
BottomSheetDialog bottomSheetDialog;
int selectedID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);
    
    radioGroup = findViewById(R.id.radioGroup);
    
    selectedID = radioGroup.getCheckedRadioButtonId();
    radioButton = findViewById(selectedID);

      if(radioButton.getText().toString().equals("Yes")){

         bottomSheetDialog = new BottomSheetDialog(Signup.this);
         bottomSheetDialog.setContentView(R.layout.bottom_file_type);
         bottomSheetDialog.setCanceledOnTouchOutside(true);
         bottomSheetDialog.show();
    }


   }
}
luk2302
  • 55,258
  • 23
  • 97
  • 137
Digvijay
  • 2,887
  • 3
  • 36
  • 86
  • No I want to check whether yes button is clicked and based on that show bottom sheet dialog. – Digvijay Nov 05 '20 at 11:41
  • 4
    Open the link, read the answer, understand what a NPE is, fix it and then maybe come back and ask another question. – luk2302 Nov 05 '20 at 11:42
  • 1
    I presume the `if` statement is running before any `RadioButton` is selected and, as such, the line `radioGroup.getCheckedRadioButtonId()` returns `0`. No `RadioButton` exists with that ID so `findViewById(selectedID)` returns `null`. Since your `radioButton` is `null`, that's the error you receive. I would suggest listening for an `OnCheckedChangeListener` listener to the `radioGroup` and putting your `if` statement there. – user959631 Nov 05 '20 at 11:56

2 Answers2

1

looks like your radioGroup.getCheckedRadioButtonId() call isn't returning valid id of checked RadioButton (probably nothing is checked at start), so findViewById(selectedID); return null. further you are trying to radioButton.getText() on null object and this is NullPointerException

probably fastest way to fix is to add android:checked="true" to one of RadioButtons declared in your activity_signup XML file

snachmsm
  • 17,866
  • 3
  • 32
  • 74
1

Add

radioGroup = findViewById(R.id.radioGroup);
radioGroup.getChildAt(0).setChecked(true);
selectedID = radioGroup.getCheckedRadioButtonId();

This selects the first item in the group during initialization.

And I suggest to change this:

// if(radioButton.getText().toString().equals("Yes"))
if(selectedID == R.id.radioButtonYes)
Tobi
  • 858
  • 7
  • 15