Sri Hari Sri Hari - 3 months ago 37
Android Question

How to check if a radiobutton is checked in a radiogroup in Android?

I need to set validation that user must fill / select all details in a page. If any fields are empty wanna show

Toast message to fill.
Now I need set validation for
RadioButton
in the
RadioGroup.
I tried this code but didn't work properly. Suggest me correct way. Thankyou.

// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
// do what you want with radioButtonText (save it to database in your case)
radioButtonText = selectedRadioButton.getText().toString();

if(radioButtonText.matches(""))
{
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
Log.d("QAOD", "Gender is Null");
}
else
{
Log.d("QAOD", "Gender is Selected");
}

Answer

If you want to check on just one RadioButton you can use the isChecked function

if(radioButton.isChecked())
{
  \\ is checked    
}
else
{
  \\ not checked
}

and if you have a RadioGroup you can use

if (radioGroup.getCheckedRadioButtonId() == -1)
{
  \\ no radio buttons are checked
}
else
{
  \\ one of the radio buttons is checked
}