I’m trying to get text from selected radiobutton. this code was working fine yesterday but now it’s returning null and I don’t understand why or what’s suddenly causing it.
Renaming variable, rewriting the code, re define variable, re initializing it does nothing to solve this.
the XML
<RadioGroup
android:id="@+id/radioGroupMurid"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:id="@+id/txtKelaminMurid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Jenis Kelamin"
android:textSize="20sp" />
<RadioButton
android:id="@+id/radioMuridLaki"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Laki-Laki" />
<RadioButton
android:id="@+id/radioMuridPerempuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Perempuan" />
</LinearLayout>
</RadioGroup>
Activity
private RadioGroup radioGroup;
protected void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstaceState);
setContentView(R.layout.murid_detail_activity);
radioGroup = (RadioGroup) findViewById(R.id.radioGroupMurid);
getRadioChecked();
}
public void getRadioChecked(){
int sexMurid = radioGroup.getCheckedRadioButtonId();
RadioButton rbSelected = (RadioButton) findViewById(sexMurid);
jenisKelamin = rbSelected.getText().toString();
}
This is really fine yesterday, I just don’t know what’s causing it? can anyone help?
3
Answers
The return type of
radioGroup.getCheckedRadioButtonId()
(as in the docs) is anint
. Anint
cannot benull
, so I think you should rely on-1
.Edit: If you’re not sure how an Android component works, just check the source code 🙂 For the
RadioGroup
, see for example: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/widget/RadioGroup.java#RadioGroup.clearCheck%28%29This occurs when RadioButton is not a direct child of RadioGroup. In your code the direct child of RadioGroup is LinearLayout. Try with the RadioGroup tag inside of LinearLayout like this: