nanjero echizen nanjero echizen - 2 months ago 11
Android Question

Android - Is there a better way to toggle a radio button on page load?

My current code fetches a database cursor when the page loads and then pre-fills the form. I am trying to check the proper radio button based whether user gender is "Male" or "Female". My 2 radio buttons is in a RadioGroup;

Java code:

public void fillData(Cursor row) {
sId = (EditText)findViewById(R.id.studentid);
fName = (EditText)findViewById(R.id.firstName);
lName = (EditText)findViewById(R.id.lastName);
gender = (RadioButton)findViewById(R.id.male);
gender2 = (RadioButton)findViewById(R.id.female);
course = (EditText)findViewById(R.id.course);
age = (EditText)findViewById(R.id.age);
address = (EditText)findViewById(R.id.address);

sId.setText(row.getString(0));
fName.setText(row.getString(1));
lName.setText(row.getString(2));
String temp = row.getString(3);
if (temp == "Male") {
gender.toggle();
} else {
gender2.toggle();
}
course.setText(row.getString(4));
age.setText(row.getString(5));
address.setText(row.getString(6));

}


With this code I am only getting the female radio button checked even if temp is "Male". I tested using Toast.maketext

Answer

You should compare string with equals method

if ("Male".equals(temp) {
        gender.toggle();
    } else {
        gender2.toggle();
    }