Android: get RadioButton value

0

Hello, I have a problem that I can not solve. I have dialog where I have a RadioGroup with 2 Radio Buttons and a OK button.

I want to get the value of the radio button selected when I click OK, but I'm getting the Exception " java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference ".

The code is as follows:

public void test(){


    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.activity_currency);
    dialog.setTitle("Test");
    dialog.show();

    //selected=new RadioButton(this.getApplicationContext());
    radioG = (RadioGroup) dialog.findViewById(R.id.radioGroup);

    Button ok = (Button) dialog.findViewById(R.id.buttonOk);
    ok.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {

            // get selected radio button from radioGroup
            int selectedId = radioG.getCheckedRadioButtonId();

            Log.d("Base ACtivity","selectedId:"+selectedId);

            // find the radiobutton by returned id
            selected = (RadioButton) findViewById(selectedId);

            String a = selected.getText().toString();

            String optionSelected = ((RadioButton) v).getText().toString();
        }
    });
}

The problem is in the String a = selected.getText().toString()); line. I have a default radioButton selected in the XML file by android:checked="true" , which causes selectedId to never be null.

Could they help?

    
asked by anonymous 23.05.2015 / 23:41

1 answer

0

The problem is that you are using the findViewById() method of Activity and not RadioGroup . The method looks for a View with this id in Activity as it does not have it returns null .

Change the line:

selected = (RadioButton) findViewById(selectedId);

for

selected = (RadioButton) radioG.findViewById(selectedId);
    
25.05.2015 / 16:48