Reputation: 172
I want to get the text from RadioButton which is Male or Female but however I got the result nullPointerExeception. Below is my code:
sex = (RadioGroup)v.findViewById(R.id.radioGroup);
int selectSex = sex.getCheckedRadioButtonId();
radioButton = (RadioButton)v.findViewById(selectSex);
String empSex = radioButton.getText().toString();
Toast.makeText(getContext(),empSex + "",Toast.LENGTH_LONG).show();
XML:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/radioGroup"
android:layout_margin="5dp"
android:orientation="horizontal"
android:weightSum="1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/male"
android:id="@+id/maleRadio"
android:textColor="@color/colorAccent"
android:layout_weight="0.3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/female"
android:id="@+id/femaleRadio"
android:textColor="@color/colorAccent"
android:layout_weight="0.3"/>
</RadioGroup>
PS: This is in Fragment page.
Upvotes: 1
Views: 102
Reputation: 1364
Can try if-else
statement
in your case, male and female
so
if(male.isChecked()){
//do somethings
}
else if(female.isChecked()){
//do somethings
}
this is the simplest and easier.
Upvotes: 1
Reputation: 436
Its an issue with your usage. You don't want to show a toast directly when your fragment is created. It should be when the user selects any radio button or user left it selected by default. You should use sex.setOnCheckedChangeListener, Answer you are looking for
is here:- https://stackoverflow.com/a/8323973/3594268
and here:- https://stackoverflow.com/a/9175703/3594268
And for context here:-https://stackoverflow.com/a/8215398/3594268 //this is your null pointer exception in Toast
Upvotes: 0