-2
private static final String TAG = MainActivity.class.getSimpleName();
EditText etName;
EditText etAge;
Button bPredict;
RadioGroup rdGroup;
Boolean maleOrFemale;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getSupportActionBar().hide();

    bPredict = (Button)findViewById(R.id.b_predict);
    etName = (EditText)findViewById(R.id.et_name);
    etAge = (EditText)findViewById(R.id.et_age);

    bPredict.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String name = etName.getText().toString();
            String age = etAge.getText().toString();
            maleOrFemale = false;
            maleOrFemale = radioGroup();
            predictIntent(name, age, maleOrFemale);
        }
    });
}

public void predictIntent(String name, String num, Boolean maleOrFemale){
    Intent toPredictActivity = new Intent(this, predict.class);
    toPredictActivity.putExtra("name", name);
    toPredictActivity.putExtra("age", num);
    toPredictActivity.putExtra("maleOrFemale", maleOrFemale);
    startActivity(toPredictActivity);
}

public boolean radioGroup(){
    Boolean maleOrFemale = true;
    int selectedId = rdGroup.getCheckedRadioButtonId();

    if (selectedId == R.id.rd_male) {
       return false;
    }else{
        return true;
    }
}

}

ERROR java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getCheckedRadioButtonId()' on a null object reference

This error is output and not sure why and would just like some help resolving this issue. Thanks in advance

alex czernenk
  • 193
  • 1
  • 8

3 Answers3

0
public boolean getSelectedGender()
{
    int checkedId = rgGender.getCheckedRadioButtonId();
    if(checkedId == R.id.rbMale) {
        return true;    // male
    }
    else {
        return false;   // female
    }
}
Piyush Malaviya
  • 1,091
  • 13
  • 17
0

You not initializing it. you need to add this to onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   getSupportActionBar().hide();

   rdGroup = (RadioGroup)findViewById(R.id.the_id_as_define_in_xml);

   bPredict = (Button)findViewById(R.id.b_predict);
   etName = (EditText)findViewById(R.id.et_name);
   etAge = (EditText)findViewById(R.id.et_age);
}
//rest of code
yshahak
  • 4,996
  • 1
  • 31
  • 37
0

1st, your RadioGroup is never initialized, 2nd, you locally redefine your class variable but never use it Boolean maleOrFemale = true;, so I guess you have to change it to maleOrFemale = true; and 3rd, the whole method can be reduced to

 public boolean radioGroup(){
   return rdGroup.getCheckedRadioButtonId() == R.id.rd_male;
 }
Droidman
  • 11,485
  • 17
  • 93
  • 141