【问题标题】:storing radio button value in sqlite database在 sqlite 数据库中存储单选按钮值
【发布时间】:2013-03-29 11:24:30
【问题描述】:

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

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

【问题讨论】:

  • 单选按钮为您提供 0 和 1 作为输出..所以将它们存储为整数
  • @CobraAjgar : 他想存储单选按钮的文本标签而不是布尔值(0 或 1)
  • @Houcine 是的,我想存储标签..我该怎么做??
  • @shiv :请看下面我的回答

标签: android radio-button


【解决方案1】:
  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. 如果您想保存一个布尔值,请测试您的 RadioButtonsselectedId 并将 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
    

编辑:

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

【讨论】:

  • 我试过这个代码..看看..rg=(RadioGroup)findViewById(R.id.radioGroup2); int selected=rg.getCheckedRadioButtonId(); rb=(RadioButton)findViewById(selected); Father_spouse=(String) rb.getText();它不存储我检查过的值..它存储活动加载时已经检查过的值..
  • 这是正常的,因为您将此代码放入您的 onCreate() 方法中,因此默认选择的值将存储在数据库中,为此,请尝试添加一个 Button 并将您的代码放入 @ 987654329@ 方法,查看我的编辑
  • selectedradiobutton 和 -1 是两种不同的数据类型。它显示错误
  • 对不起,我犯了一个简单的愚蠢错误,if 子句应该在之前,请参阅我的编辑 :)
  • 在 xml 文件中保持选中的单选按钮选项有什么不同吗???
猜你喜欢
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多