How to programmatically select RadioButton in an activity
Asked Answered
C

2

9

In my project, I get the value of the gender from the database as 0 and 1.
0 for male and 1 for female.
Based on this values, I need to check the corresponding RadioButton in a RadioGroup.
If 0 is pressed, radio0 will be checked or radio1 will be checked.
I don't know how to check the radio button based on this string values...
This is the code I tried:

      String gendd=ViewProfileActivity.participantview.get(4);
      System.out.println("Gender:::::"+gendd);

      male=(RadioButton)findViewById(R.id.radio0);
       female=(RadioButton)findViewById(R.id.radio1);
       if(gendd.equals("0")){

           male.setSelected(true);
           female.setSelected(false);
       }
       else
           {
           male.setSelected(false);

           female.setSelected(true);

           }

But it fails. Can anyone help me?

Caressive answered 31/12, 2013 at 14:44 Comment(3)
Code look oke, have you debugged your code? What was the value of gendd? Did it enter the if or else block?Medlin
it got values like 0 or 1Caressive
Top tip: use "0".equals(gendd) in string comparison better, this way the first string will never be null and you might avoid unpleasant NullPointers in the futurePseudo
C
14

Try this.

   if(gendd.contains("0"))
    {
       male.setChecked(true);
       female.setChecked(false);
   }
   else
   {
       male.setChecked(false);
       female.setChecked(true);
  }
Consul answered 31/12, 2013 at 14:53 Comment(0)
R
9

You shoud use check(radioButtonId) method on parent RadioGroup.

E.g.

radioGroup.check(gendd.equals("0") ? R.id.radio0 : R.id.radio1);

(assuming the comparison holds as the types haven't been mentioned)

Righthanded answered 31/12, 2013 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.