getCheckedRadioButtonId() returning useless int? - android

I have a button's onClickListener that needs to detect which radiobutton was selected when the user clicks the button. Currently, the Log.v you see below in the onClickListener is not returning a useless bit of info:
This is clicking submit three times with a different radio selected each time:
04-27 19:24:42.417: V/submit(1564): 1094168584
04-27 19:24:45.048: V/submit(1564): 1094167752
04-27 19:24:47.348: V/submit(1564): 1094211304
So, I need to know which radioButton is actually selected - is there a way to get the object of the radiobutton? I want to be able to get it's id# from XML, as well as its current text.
Here's the relevant code:
public void buildQuestions(JSONObject question) throws JSONException {
radioGroup = (RadioGroup) questionBox.findViewById(R.id.responseRadioGroup);
Button chartsButton = (Button) questionBox.findViewById(R.id.chartsButton);
chartsButton.setTag(question);
Button submitButton = (Button) questionBox.findViewById(R.id.submitButton);
chartsButton.setOnClickListener(chartsListener);
submitButton.setOnClickListener(submitListener);
TagObj tagObj = new TagObj(question, radioGroup);
submitButton.setTag(tagObj);
}
public OnClickListener submitListener = new OnClickListener() {
public void onClick(View v) {
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(activity)) {
TagObj tagObject = (TagObj) v.getTag();
RadioGroup radioGroup = tagObject.getRadioGroup();
JSONObject question = tagObject.getQuestion();
Log.v("submit", Integer.toString(radioGroup.getCheckedRadioButtonId()));
SubmitTask submitTask = new SubmitTask((Polling) activity, question);
submitTask.execute();
}
}
};

getCheckedRadioButtonId() returns the id of the RadioButton(or -1 if no RadioButtons are checked) that is checked in the Radiogroup. If you set distinct ids to the RadioButons in the layout then you will try to match those ids with the return of the method to see which one is checked:
//field in the class
private static final int RB1_ID = 1000;//first radio button id
private static final int RB2_ID = 1001;//second radio button id
private static final int RB3_ID = 1002;//third radio button id
//create the RadioButton
RadioButton rb1 = new RadioButton(this);
//set an id
rb1.setId(RB1_ID);
int btn = radioGroup.getCheckedRadioButtonId();
switch (btn) {
case RB1_ID:
// the first RadioButton is checked.
break;
//other checks for the other RadioButtons ids from the RadioGroup
case -1:
// no RadioButton is checked inthe Radiogroup
break;
}

store the checked ID, then compare it to each button using the function radioButton.getID() using a switch statement or if-else chains

I am setting initial checked radioButton in RadioGroup xml
<RadioGroup
android:id="#+id/rgCustomized"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:checkedButton="#+id/rbNotCustomized"
android:orientation="horizontal">
<RadioButton
android:id="#+id/rbCustomized"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:text="#string/yes" />
<RadioButton
android:id="#+id/rbNotCustomized"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/no" />
</RadioGroup>
And I identify which radioButton is selected like this
rgCustomized.checkedRadioButtonId==rbCustomized.id

I think relying on what radioGroup.getCheckedRadioButtonId() returns is not good practice if you want to store it into the database or to use it.
Because:
getCheckedRadioButtonId() value will keep changing for each RadioButton and if there are two similar values (two views in the same hierarchy) Android will choose the first one. Unless you provided a unique Ids with method generateViewId() and set it to the view with setId().
getCheckedRadioButtonId() will return unknown value.
Therefore
Switching on radioGroup.getCheckedRadioButtonId() and implement your custom values to each selection then use that custom value, not the View Id.
Example to use values from selected Radio Button:
int selected = -1;
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.one_radioButton:
selected = 0;
break;
case R.id.two_radioButton:
selected = 1;
break;
case R.id.three_radioButton:
selected = 2;
break;
}
// return a custom value you specific
Log.d(TAG, "selectedBox: " + selectedBox);
// return a random unknown number value
Log.d(TAG, "radioGroup.getCheckedRadioButtonId(): " + radioGroup.getCheckedRadioButtonId());
Example to populate selected RadioButton to UI:
switch (selected) {
case 0:
oneRadioButton.setChecked(true);
break;
case 1:
twoRadioButton.setChecked(true);
break;
case 2:
threeRadioButton.setChecked(true);
break;
}

Related

Change the color of radioButon when one of the options is selected in Android

I have developed a dynamic UI of survey questions, where I have questions answering "YES" or "NO". For questions having answers as Yes/No, I have taken radio-group for user input. How to change the color of the Radio button Highlight color for a specific question , when a specific radioGroup option(Yes/no) is selected everytime? I have Done the following implementation, but it is not working.
final AppCompatRadioButton[] rb = new AppCompatRadioButton[2];
final RadioGroup rg = new RadioGroup(context); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
String[] options = context.getResources().getStringArray(R.array.radio_options_yes_no);
if (questionList.get(j).getQuestionId().matches("3|16|24"))
{
rb[0].setHighlightColor(context.getResources().getColor(R.color.red));
rb[0].setTextColor(context.getResources().getColor(R.color.red));
}
//for yes as unsafe option
else if (questionList.get(j).getQuestionId().matches("21|23|30|32")){
rb[1].setHighlightColor(context.getResources().getColor(R.color.red));
rb[1].setTextColor(context.getResources().getColor(R.color.red));
}
add this onclick on all radio button in xml
android:onClick="onRadioButtonClicked"
now add onRadioButtonCliked method
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
now apply your logic here
and change the color using this code
.setTextColor(context.getResources().getColor(R.color.red));
here is the link for further reading
for radio button circle color change

Android -get radio button id based on value

I want to highlight right and wrong option when user clicks a button after checking an radio button. If that option is right, highlight. Else highlight right option.
Is there any way to get radio button id in a group based on its value? Or Do I need to use switch case?
I searched enough but not able to find out what I need.
Edit
I have simple layout which contains one question, 4 choices, one button. User check a radio button and click the check button. If user selects wrong option, highlight the correct option. I know what is correct option by value.
choice1, choice2, choice3, choice4 are four radio buttons. User checks choice3. But choice2 is correct. How do I select choice2 by value in this radio group.
group.getRadioButtonId("choice2")
Anything similar to this?
You could iterate through the children of your RadioGroup to get the required one:
int count = radioGroup.getChildCount();
for (int i = 0 ; i < count; i++) {
RadioButton button = (RadioButton) radioGroup.getChildAt(i);
if (button.getText().equals("choice2")) {
int id = button.getId(); // the ID you're looking for
}
}
You Can check like this
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
int rbId = group.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rbId);
switch (group.getId()) {
case R.id.radiogroupID:
if (rb.getText().toString().equalsIgnoreCase("right")) {
// your logic
} else {
//your logic
}
}
}
you can use these line. its working for me
int checkedId = radioGroup.getCheckedRadioButtonId();
View radioButton = radioGroup.findViewById(checkedId);
int radioId = radioGroup.indexOfChild(radioButton);
RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
First check which option is true. hear choice 2 OK. set by default is checked true and than check user checked value . if user select other option than display message and pass true option we already checked true
Create an int array with all the ids of the radiobutton
int[] rb_IDs=new int[]{R.id.rb1,R.id.rb2,R.id.rb3};
Then inside your button click :
RadioGroup rg=(RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i=0;i<rb_IDs.length;i++)
{
RadioButton rb=(RadioButton)findViewById(rb_IDs[i]);
if (rb.getText().toString().equals("YOUR CORRECT ANSWER")&&!rb.isChecked())
{
//
//Do your thing
//
//ID of the correct answer Radiobutton is
int id=rb_IDs[i];
//HighLighting the answer
rb.setBackgroundColor(Color.parseColor("#00ff00"));
break;
}
}
}
});

onclick not working in resume method

i have a problem in my application, i have a formulaire whish a user should fill information and save it to database,i have both Edit Text and Radio Button :
rm_1 = (EditText) findViewById(R.id.rm_1);
rm_2 = (EditText) findViewById(R.id.rm_2);
rm_3 = (EditText) findViewById(R.id.rm_3);
rm_13_1 = (RadioButton) findViewById(R.id.rm_13_1);
rm_13_2 = (RadioButton) findViewById(R.id.rm_13_2);
rm_14_1 = (RadioButton) findViewById(R.id.rm_14_1);
rm_14_2 = (RadioButton) findViewById(R.id.rm_14_2);
rm_14_3 = (RadioButton) findViewById(R.id.rm_14_3);
i have a method Onclick whish associate each radio buton selected with a value :
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((Checkable) view).isChecked();
switch (view.getId()) {
case R.id.rm_13_1:
if (checked)
a = 0;
break;
case R.id.rm_13_2:
if (checked)
a = 1;
break;
case R.id.rm_14_1:
if (checked)
b = 0;
break;
case R.id.rm_14_2:
if (checked)
b = 1;
break;
case R.id.rm_14_3:
if (checked)
b = 2;
break;
case R.id.rm_14_4:
if (checked)
b = 3;
break;
}
until now everything works fine, the user writes in the edit text and select the radio button , and in database i find the same information.
in order to save the data entered by the user i did used shared preferences, so the text writing by the user and radio button selected appear again when the user returns to the activity.
That's when the issue occurs when a user change the activity , so if he returns to the activity he finds the radio button already selected but when he click on save button the value he gets in database is zero, it is like the methode :
public void onRadioButtonClicked(View view)
is not working, i don't know why ?? the user need to click again on radio button to have the values assigned in the method onRadioButtonClicked(View view), so how to solve that ?
this is where i save data :
Button bton = (Button) findViewById(R.id.ajoutUn);
bton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ajouter(v);
}
public void ajouter(View v) {
db.open();
db.insertMENAGE(rm_1ts, rm_2ts, rm_3ts, rm_4ts, rm_5ts,
rm_6ts, rm_7ts, rm_8ts, rm_9ts, rm_10ts, rm_11ts,
a, b, rm_14_4_autrets, rm_15ts);}}
And the method in database is :
public long insertMENAGE(String Region, String Provence_prefecture , String Commune_Arrondissement ,String N_district, String N_M_district , String N_menage_logement, String Adresse_menage , String Nom_Enqueteur, String code_enquêteur , String Date_realisation_enquête, String Nom_controleur , String Date_controle, int echantillon_principal, int Statut_enquêté , String autre, String Observations ) {
ContentValues initialValues = new ContentValues();
initialValues.put(col_Commune_Arrondissement,Commune_Arrondissement);
initialValues.put(col_N_district,N_district);
initialValues.put(col_N_M_district,N_M_district);
initialValues.put(col_N_menage_logement,N_menage_logement);
initialValues.put(col_Adresse_menage,Adresse_menage);
initialValues.put(col_Nom_Enqueteur,Nom_Enqueteur);
initialValues.put(col_code_enquêteur ,code_enquêteur);
initialValues.put(col_Date_realisation_enquête,Date_realisation_enquête);
initialValues.put(col_Nom_controleur,Nom_controleur);
initialValues.put(col_Date_controle,Date_controle);
initialValues.put(col_echantillon_principal,echantillon_principal);
initialValues.put(col_Statut_enquêté,Statut_enquêté);
initialValues.put(col_Observations,Observations);
return db.insertOrThrow(MENAGE,null, initialValues);
}
Check all your radio button values at your onResume() method like following, and assigning values to your variable.
if(rm_13_1.isChecked())
{
}
else if(rm_13_2.isChecked())
{
}
else if(rm_14_1.isChecked())
{
}
else if(rm_14_2.isChecked())
{
}
else if(rm_14_3.isChecked())
{
}
Hope it will work
First of all I'm posting this an answer because the text is too large.
Either there's some meaningful code that we're not seeing, or there's a problem understanding a few things.
The method onRadioButtonClicked(View view) is only called when the user clicks the radioButton. When the user comes back from another Activity the button is already selected. This is correct, and this is how it should behave. As far as I can see, this code only affects variables 'a' and 'b'.
On the other hand you say that you have a separate 'save' button. When the user comes back from another Acivity, variables 'a' and 'b' should preserve their values, and the results of your 'save' code should work.
I know this is not an answer, just a few insights that hopefully help you in some way.

storing radio button value in sqlite database

i have a radio group with two radio buttons in it. I want to get the value of the radio button and then store it in the database..how do i do that?? Pls help! I searched for it but all in vain!
I tried this code but my activity stops working after using it
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();
}
if you want to store the text label of your RadioButton then use this :
// 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();
}
if you want to save a boolean value so test on the selectedId of your RadioButtons and save a 0 or 1 to your database column (Example of two radio buttons to enable/disable updates) :
// 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
EDIT :
if you should control the selected value and when send it to database, see this tutorial

How to get the id of selected radio button in android?

I am working on quiz application in android. We have created Select.java page which displays the questions and options(with radio buttons) from sqlite database. Also we created a header.java file for displaying buttons i.e back and next buttons for the Select.java page.
Here we need to get the selected radio button id and need to send that to Header class. Because header class consists of the next button onclick action. Once the next button is clicked the selected radio button value has to be stored in arraylist. We created radio buttons in Select.java class. So my question is how to get the selected radio button id into that next button click action. Please help me regarding this.
Thanks in Advance.
Your layout xml file should be like this
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RadioGroup
android:orientation="vertical"
android:id="#+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option1"
android:text="Option1"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option2"
android:text="Option2"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option3"
android:text="Option3"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option4"
android:text="Option4"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option5"
android:text="Option5"
/>
</RadioGroup>
</LinearLayout>
Add the below ode in your Activity
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId);
String text = checkedRadioButton.getText().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
I know it's a old question but i don't see my answer in anywhere and i found it more simple than others..
so here we go:
int myRadioChecked;
if(radioGroup.getCheckedRadioButtonId() == findViewById(R.id.YOUR_RADIO_BUTTON).getId()) {
/**Do Stuff*/
//ex.: myRadioChecked = 1;
}
final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.MyRadioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int selectedId = radioGroup.getCheckedRadioButtonId();
Log.i("ID", String.valueOf(selectedId));
}
});
In RadioGroup Class you can use method getCheckedRadioButtonId();
RadioGroup rg = findViewById(R.id.radioGroup);
rg.getCheckedRadioButtonId();
Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
Hmmm, just add one more member variable in UserBO to store selected answer.
Class UserBO {
private int userID;
private String userName;
private String question;
private String option1;
private String option2;
private String option3;
private int answerID;
//create getter and setters for above member variables
}
then within onclick listener of Adapter class, do like as following
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup,
int radioButtonID) {
switch(radioButtonID) {
case R.id.option1:
listItem.setAnswerID(1);
break;
case R.id.option2:
listItem.setAnswerID(2);
break;
}
}
});
then change your header constructor to receive userarraylist (which contains user details with answer)
ArrayList<USerBO> userList;
Header(Context context, AttributeSet attrs, ArrayList<UserBO> userALt) {
userList = userAL;
}
//on next button click
onclick() {
for(UserBO userObj: userList) {
if (userObj.getAnswerID != 0)
Log.d("AnswerID", userObj.getAnswerID);
}
}
it just like sudo code.. i hope this will help u..
you can get the id of selected button by the following this.Here
int position = group.indexOfChild(radioButton);
will give you the id.Also you can to Toast to see id like this
Toast.makeText(MainActivity.this,"Id of radio button"+position+, Toast.LENGTH_SHORT).show();
This will pop up - "Id of radio button you clicked is 0" if you clicked first button.
This is the best way:
RadioButton button = findViewById(v.getId());

Categories

Resources