Heretic Monk
Heretic Monk

Reputation: 397

Radio Buttons Set checked state through code

I have three Radio buttons to specify the gender, Male Female and Others. I save this data into my DB as 1 for Male, 2 for female and three for others based on user selection. This is reflected in the profile page, now when I want to edit the profile I want to auto-populate all the fields of my profile page in an editable manner, the user only changes the fields he wants to. Although I am able to fetch the values of 1,2,3 for gender from my database but I am not able to populate the specified radio button as checked. I tried the following:

String M = (c.getString(c.getColumnIndexOrThrow("Gender")));
RadioGroup rb1 = (RadioGroup)findViewById(R.id.radiogroup1);

if(M.equals(1)){
    rb1.check(R.id.radiobutton3);
    RadioButton rbu1 =(RadioButton)findViewById(R.id.radiobutton3);
    rbu1.setChecked(true);
}
else if(M.equals(2)){
    rb1.check(R.id.radiobutton4);
    RadioButton rbu2 =(RadioButton)findViewById(R.id.radiobutton4);
    rbu2.setChecked(true);
}
else if(M.equals(3)){
    rb1.check(R.id.radiobutton5);
    RadioButton rbu3 =(RadioButton)findViewById(R.id.radiobutton5);
    rbu3.setChecked(true);
}

Upvotes: 7

Views: 36184

Answers (3)

Siva K
Siva K

Reputation: 4968

You can use either radioButton.setChecked(true); or radiobutton.setSelected(true);

Don't give rb1, here in your code rb1 refers to RadioGroup, set names for radio buttons.

String M = "3";
RadioGroup rb1 = (RadioGroup)findViewById(R.id.radioGroup1);
RadioButton rbu1 =(RadioButton)findViewById(R.id.radio0);
RadioButton rbu2 =(RadioButton)findViewById(R.id.radio1);
RadioButton rbu3 =(RadioButton)findViewById(R.id.radio2);

if(M.equalsIgnoreCase("1"))
{
    rbu1.setChecked(true);
}
else if(M.equalsIgnoreCase("2")){

    rbu2.setChecked(true);
}
else if(M.equalsIgnoreCase("3"))
{    
    rbu3.setChecked(true);
}

Upvotes: 14

selva_pollachi
selva_pollachi

Reputation: 4217

This is for set checked.

radioButton.setChecked(true);

This is for getting value of checked radiobutton

RadioGroup rg=(RadioGroup) findViewById(R.id.radioGroup1);

rg.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup arg0, int id)
{
RadioButton checkedRadioButton = (RadioButton)rg.findViewById(id);

boolean isChecked = checkedRadioButton.isChecked();

if (isChecked)
{
Toast.makeText(getApplicationContext(), 
           checkedRadioButton.getText(),Toast.LENGTH_LONG).show();
}
}});

Upvotes: 2

SubbaReddy PolamReddy
SubbaReddy PolamReddy

Reputation: 2113

try this code:

radioButton.setChecked(true);

radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
int selectedId = radioSexGroup.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(selectedId);
sex = rb.getText().toString().trim();

Upvotes: 1

Related Questions