0

我有一个带有两个单选按钮的单选组。我想获取单选按钮的值,然后将其存储在数据库中..我该怎么做?请帮忙!我搜索了它,但一切都是徒劳的!我尝试了此代码,但使用它后我的活动停止工作

rg=(RadioGroup)findViewById(R.id.radioGroup2);
if(rg.getCheckedRadioButtonId()!=-1)
    {
        int id=rg.getCheckedRadioButtonId();
        View radioButton=rg.findViewById(id);
        int radioid=rg.indexOfChild(radioButton);
        RadioButton btn = (RadioButton) rg.getChildAt(radioid);
        Father_spouse=(String)btn.getText();
    }
4

1 回答 1

2
  1. 如果你想存储你的文本标签RadioButton然后使用这个:

    // get selected radio button from radioGroup
    int selectedId = radioGroup.getCheckedRadioButtonId();
    
    if(selectedId != -1) {    
       // find the radiobutton by returned id
       selectedRadioButton = (RadioButton) findViewById(selectedId);
    
       // do what you want with radioButtonText (save it to database in your case)
       String radioButtonText = selectedRadioButton.getText();
    }
    
  2. 如果您想保存一个布尔值,请测试selectedId您的RadioButtons并将 0 或 1 保存到您的数据库列(启用/禁用更新的两个单选按钮的示例):

    // get selected radio button from radioGroup
    int selectedId = radioGroup.getCheckedRadioButtonId();
    boolean isAllowUpdate = false;
    switch(selectedId) {
        case R.id.radioAllowUpdate : isAllowUpdate = true; break;
        case R.id.radioDisableUpdate : isAllowUpdate = false; break;
    }
    
    //save it to database 
    if(isAllowUpdate)
       // true ==> save 1 value
    else 
       // false ==> save 0 value
    

编辑 :

如果您应该控制所选值并将其发送到数据库,请参阅本教程

于 2013-03-29T11:37:54.373 回答