user1943977
user1943977

Reputation:

Dynamically setting RadioButton checked

I'm developing Android app and I have one problem. I have Radiobutton group:

<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/niezakonczoneRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="14dp"
android:layout_marginTop="0dp"
android:onClick="niezakonczoneRadio"
android:text="Niezakończone" />

<RadioButton
android:id="@+id/zakonczoneRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="14dp"
android:layout_marginTop="0dp"
android:onClick="zakonczoneRadio"
android:text="Zakończone" />

</RadioGroup>

And I want to dynamically check one of it in if...else statement (in onCreate), like this:

if (status=="Zakończone"){
          RadioButton radioTak = (RadioButton) findViewById(R.id.zakonczoneRadio);

          radioTak.setChecked(true);
          status_radio="1";  
      } else {
          RadioButton radioNie = (RadioButton) findViewById(R.id.niezakonczoneRadio);
          radioNie.setChecked(true);
          status_radio="0";  
      };

Even if "status" variable is "Zakończone", the niezakonczoneRadio is checked. What is problem here? Generally there is checked one button all the time, no matters which value has the variable. Thanks for help.

Upvotes: 0

Views: 2713

Answers (2)

Simon Dorociak
Simon Dorociak

Reputation: 33505

Your problem is obviously condition:

if (status == "Zakończone") { }

This always return false(you are comparing references not String values). Remember, whenever you want to compare Strings, you have to use equals() method.

So change it to:

if (status.equals("Zakończone")) { // or equalsIgnoreCase() }

Now it'll work. I strongly recommend you to read this:

And remember one golden rule: Always you want to compare Strings equals() becomes your the closest friend.

Upvotes: 1

smk
smk

Reputation: 5842

status.equals("Zakończone") 

Use the string equals method

Upvotes: 0

Related Questions