0

I keep getting an error when trying to set value to a variable from a RadioButton. The error is the following:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aquino.myapp3, PID: 17484
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
    at com.example.aquino.myapp3.activities.MainActivity.postDataToSQLite(MainActivity.java:114)
    at com.example.aquino.myapp3.activities.MainActivity.onClick(MainActivity.java:92)
    at android.view.View.performClick(View.java:4780)

The line that logcat indicates the error seems to be this:

measurement.setBodyPlace(radioButton.getText().toString());

I have initialized the views:

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
RadioButton radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());

measurement is an instantiation of Measurement class, which looks like:

public class Measurement{
    private String rbBodyPlace;

    public void setBodyPlace(String rbBodyPlace){
        this.rbBodyPlace = rbBodyPlace;
    }
}

Any help is welcome, thank you!

Lua
  • 57
  • 8

2 Answers2

0

You have not initialized your radio button.

EDIT (thanks @Tura):

try this in your onCreate() in Activity:

radioButton = findViewById(R.id.radio_button);

Fill the id section with your id described in the xml file.

Antonio Vlasic
  • 337
  • 3
  • 15
0

The error was because of initializing RadioGroup and RadioButton (also taking selected id) the same time, i.e. before user have selected any radio button. That was why android system was returning null value. To solve this mistake, I made the initialization of RadioGroup first, then I initialized RadioButton only after user had clicked/made some action.

Lua
  • 57
  • 8