RadioGroup 查找选定的 ID

RadioGroup finding selected id

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;
    }
}

}

错误 java.lang.NullPointerException: 尝试在空对象引用

上调用虚拟方法'int android.widget.RadioGroup.getCheckedRadioButtonId()'

此错误已输出,不确定原因,希望得到一些帮助来解决此问题。提前致谢

public boolean getSelectedGender()
{
    int checkedId = rgGender.getCheckedRadioButtonId();
    if(checkedId == R.id.rbMale) {
        return true;    // male
    }
    else {
        return false;   // female
    }
}

你没有初始化它。您需要将其添加到 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

第一,你的 RadioGroup 从未被初始化,第二,你在本地重新定义了你的 class 变量但从未使用它 Boolean maleOrFemale = true;,所以我想你必须将它更改为 maleOrFemale = true; 和第 3 个,整个方法可以简化为

 public boolean radioGroup(){
   return rdGroup.getCheckedRadioButtonId() == R.id.rd_male;
 }