2

How to get value of selected radioButton? I tried using buttonGroup1.getSelection().getActionCommand() (as posted in some of answers here) but it is not working. Also, i am temporarily using this code but i want to know is this a good practice or not?

//Consider that maleRButton and femaleRButton are two radioButtons of 
//same buttonGroup
String getGender()
{
    if(maleRButton.isSelected())
    {
        return "Male";
    }
    else if(femaleRButton.isSelected())
    {
        return "Female";
    }
    else
    {
        return null;
    }
}

4 Answers 4

6

I tried using buttonGroup1.getSelection().getActionCommand()

That approach will work, but for some reason it looks like you manually need to set the action command when you create the button. For example:

JRadioButton maleButton = new JRadioButton( "Male" );
maleButton.setActionCommand( maleButton.getText() );

This acutally seems like a bit of a bug to me since usually the action command defaults to the text if the action command is not set.

5

If you have several buttons you probably should do it this way :

String getSelectedButton()
{  
    for (Enumeration<AbstractButton> buttons = buttonGroup1.getElements(); buttons.hasMoreElements();) {
        AbstractButton button = buttons.nextElement();
        if (button.isSelected()) {
                return button.getText();
        }
    }
    return null;
}
1

String gender=group.getSelection().getActionCommand();

It will work but it show null value.

1
  • 1
    I just set radio1.setActionCommand("button1") and it will work (radio1is my JRadioBurron name) Mar 16, 2017 at 9:54
0
int selectedRadioButtonID = radio_group.getCheckedRadioButtonId();
// If nothing is selected from Radio Group, then it return -1
if (selectedRadioButtonID != -1) {
RadioButton selectedRadioButton = findViewById(selectedRadioButtonID);
String selectedRadioButtonText = selectedRadioButton.getText().toString();
answerList.add(selectedRadioButtonText);
} else {
Toast.makeText(this, "select radio button", Toast.LENGTH_SHORT).show();
                return false;
}

For Deatils, check this

Not the answer you're looking for? Browse other questions tagged or ask your own question.