1

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.

David Adam
  • 172
  • 1
  • 12
  • Possible duplicate of [How to set OnClickListener on a RadioButton in Android?](https://stackoverflow.com/questions/8323778/how-to-set-onclicklistener-on-a-radiobutton-in-android) – Abhinav Aggarwal May 11 '18 at 18:55

2 Answers2

1

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.

Kopi Bryant
  • 1,300
  • 1
  • 15
  • 30
0

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

Abhinav Aggarwal
  • 416
  • 3
  • 14
  • Can you do me a favor to post the code? However, if i using the radioGroup.setOnCheckedListener, the radioGroup show nullPointerException error. – David Adam May 12 '18 at 03:15
  • Sorry for late reply, If you still have the issue please post your whole java class and XML. I will correct it. Since the block which you have posted suggested the solution I have already given – Abhinav Aggarwal May 14 '18 at 10:23