0

What code do I need to write to have my listener call out the checked Radio Button? Here's my code:

public class TabFragment1 extends Fragment {

    RadioGroup radioGroup;
    RadioButton radioButtonJa, radioButtonNee;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        radioGroup = (RadioGroup)v.findViewById(R.id.radioGroup);
        radioButtonJa = (RadioButton)v.findViewById(R.id.radio_hoogteverschillen_ja);
        radioButtonJa.setChecked(true);
        radioButtonNee = (RadioButton)v.findViewById(R.id.radio_hoogteverschillen_nee);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId)
            {
                boolean isChecked1 = radioButtonJa.isChecked();
                boolean isChecked2 = radioButtonNee.isChecked();
                if (isChecked1){
                    radioButtonJa.setChecked(true);
                    Toast.makeText(getActivity().getBaseContext(), "Ja", Toast.LENGTH_SHORT).show();
                }
                else if (isChecked2){
                    radioButtonNee.setChecked(true);
                    Toast.makeText(getActivity().getBaseContext(), "Nee", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(getActivity().getBaseContext(), "Geen", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

When starting my app, it should create a toast but it doesn't. It only creates one when I first click on the other Radio Button. This was also the case with android:checked(true) in the layout file (instead of radioButtonJa.setChecked(true);). How can I get the toast to appear when I open my application?

Arjen de Jong
  • 1,051
  • 1
  • 7
  • 15

1 Answers1

0
        int radioButtonID = radioGroup.getCheckedRadioButtonId();
        View radioButton = radioGroup.findViewById(radioButtonID);
        int idx = radioGroup.indexOfChild(radioButton);

        RadioButton r = (RadioButton)  radioGroup.getChildAt(idx);
        String selectedtext = r.getText().toString();

        Toast.makeText(getApplicationContext(), selectedtext, Toast.LENGTH_SHORT).show();

Put this code in your onCreateView() method just after setting up the variables for Radio Buttons. This will do the trick.

Taken from here.

Community
  • 1
  • 1
  • This produces a `java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference` for me. – Arjen de Jong Jan 13 '16 at 22:35