Issue
I want to set a String variable value to 1,2,3 when user selected male, female or unclassified respectively from the radio group.
Right now I am doing it this way but even if I select a radio button it set the variable value as null
Code:
RadioGroup genderGroup;
RadioButton male, female, unclassified;
String strGender;
genderGroup = findViewById(R.id.genderGroup);
male = findViewById(R.id.genderMale);
female = findViewById(R.id.genderFemale);
unclassified = findViewById(R.id.genderUnclassified);
if (genderGroup.getCheckedRadioButtonId() == -1) {
strGender = null; //no buttons selected
} else {
if (male.isChecked()) { // one of the radio buttons is checked
strGender = "1";
} else if (female.isChecked()) {
strGender = "2";
} else if (unclassified.isChecked()) {
strGender = "3";
}
}
When I print the value after selecting any radio button it shows null. If you know how to do this please help :) thanks.
Solved Thanks to Nilesh. Correct code is:
genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.genderMale) {
strGender = "1";
} else if (checkedId == R.id.genderFemale) {
strGender = "2";
}
}
});
Solution
you need to use RadioGroup.OnCheckedChangeListener
Interface definition for a callback to be invoked when the checked radio button changed in this group.
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.genderMale) {
strGender = "1";
} else if (checkedId == R.id.genderFemale) {
strGender = "2";
}
}
});
Answered By - AskNilesh
Answer Checked By - Pedro (JavaFixing Volunteer)