0
Hi, I have a problem I can’t solve.
I have a dialog
where I have a RadioGroup
with 2 Radio Buttons
and a button OK
.
I want to get the radio button value 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 on the line String a = selected.getText().toString());
. I have by default a radiobutton selected in the XML file via android:checked="true"
, what makes it selectedId
never be null.
I wonder if they could help?
The error will not be on the line
String optionSelected = ((RadioButton) v).getText().toString();
? Note thatv
is a button and you’re doing the cast for Radiobutton– ramaral
@ramaral, yes the error is there, the v is a button?
– porthfind
It is because the Onclicklistener, in this case, it has been associated with a button:
ok.setOnClickListener(new View.OnClickListener()....
– ramaral
@ramaral not realizing.. was associated with the ok button, because I want when you click the ok button, get the value of the radiobutton
– porthfind
Yes that’s correct, however
v
is a button. I will put an answer.– ramaral
No need to put answer, comment or delete the line
String optionSelected = ((RadioButton) v).getText().toString();
the text of Radiobutton selected is in the stringa
– ramaral
@ramaral problem is even in line String a = Selected.gettext(). toString();
– porthfind
When you said you were going to post an answer, it was because you thought your code might have a problem. I did some tests and found nothing wrong. However I took the principle that
radioG
is a Radiogroup and that has a Radiobutton selected. What is written in log by lineLog.d("Base ACtivity","selectedId:"+selectedId);
?– ramaral
@ramaral, selectedId:2131296322
– porthfind