-1

I do have a fragment inflating a layout that contains a single button.I added radiogroup and radiobuttons dynamically in onCreateView() method.But the problem is in onclicklistener of that button. While retrieving for radiobutton text that's checked in a radioGroup I do get nulpointerexception.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View v =  inflater.inflate(R.layout.variant_choose,null);

    Button button = (Button) v.findViewById(R.id.apply_variant_button);

    LinearLayout ll = (LinearLayout) v.findViewById(R.id.layout_for_radiobuttons_in_variants);

    final RadioGroup rg = new RadioGroup();
    rg.setId(View.generateViewId());
    rg.setOrientation(LinearLayout.HORIZONTAL);
    RadioButton rb[] = new RadioButton[5];
    for(int j=0;j<5;j++){

            rb[j] = new RadioButton(getActivity());
            rb[j].setId(View.generateViewId());
            rb[j].setText(j);
            rg.addView(rb[j]);       

    }

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                RadioButton rb1 = (RadioButton) v.findViewById(rg.getCheckedRadioButtonId());

                String str1 = (String) rb1.getText();

        }
    });

  return v;
}

View v contains dynamically created radiogroup and button till onCreateView. But later in onclicklistener it's not the case.It only contains button that's defined in xml file? What could be the reason for this? How can I get the text of checked radiobutton?

A Sdi
  • 665
  • 2
  • 10
  • 24
Mani teja
  • 31
  • 8
  • You should work with Tags not with ids. – Tiago Dávila Dec 13 '16 at 15:09
  • Might I point to this SO post: http://stackoverflow.com/questions/8460680/how-can-i-assign-an-id-to-a-view-programmatically I think it can help you understand IDs a bit better and help you also discover some ways to implement them programmatically. – Yoshi_64 Dec 13 '16 at 15:11

1 Answers1

0

I believe you don't have a checked RadioButton in your RadioGroup therefore rg.getCheckedRadioButtonId() returns -1, then findViewById returns null.

Try something like rb[0].setChecked(true); after filling the array.

  • Yeah it could be a reason.But I checked a `radiobutton`. It works fine outside `onclicklistener`within its scope but no in `onClick `method – Mani teja Dec 13 '16 at 15:16