How to check if a radiobutton is checked in a radiogroup in Android?

AndroidRadio ButtonRadio Group

Android Problem Overview


I need to set validation that user must fill / select all details in a page. If any fields are empty wanna show Toast message to fill. Now I need set validation for RadioButton in the RadioGroup. I tried this code but didn't work properly. Suggest me correct way. Thankyou.

// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
// do what you want with radioButtonText (save it to database in your case)
radioButtonText = selectedRadioButton.getText().toString();
		
if(radioButtonText.matches(""))
{
	Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
	Log.d("QAOD", "Gender is Null");
}
else
{
	Log.d("QAOD", "Gender is Selected");
}

Android Solutions


Solution 1 - Android

If you want to check on just one RadioButton you can use the isChecked function

if(radioButton.isChecked())
{
  // is checked    
}
else
{
  // not checked
}

and if you have a RadioGroup you can use

if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}
else
{
  // one of the radio buttons is checked
}

Solution 2 - Android

All you need to do is use getCheckedRadioButtonId() and isChecked() method,

if(gender.getCheckedRadioButtonId()==-1)
{
    Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
    // get selected radio button from radioGroup
    int selectedId = gender.getCheckedRadioButtonId();
    // find the radiobutton by returned id
    selectedRadioButton = (RadioButton)findViewById(selectedId);
    Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}

https://developer.android.com/guide/topics/ui/controls/radiobutton.html

Solution 3 - Android

Use the isChecked() function for every radioButton you have to check.

RadioButton maleRadioButton, femaleRadioButton;

maleRadioButton = (RadioButton) findViewById(R.id.maleRadioButton);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleRadioButton);

Then use the result for your if/else case consideration.

if (maleRadioButton.isChecked() || femaleRadioButton.isChecked()) {
     Log.d("QAOD", "Gender is Selected");
} else {
    Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
    Log.d("QAOD", "Gender is Null");
}
    

Solution 4 - Android

  rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch(i) {
                case R.id.type_car:
                    num=1;
                    Toast.makeText(getApplicationContext()," Car",Toast.LENGTH_LONG).show();
                    break;
                case R.id.type_bike:
                    num=2;
                    Toast.makeText(getApplicationContext()," Bike",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    });

Solution 5 - Android

Try to use the method isChecked();

Like,

> selectedRadioButton.isChecked() -> returns boolean.

Refere here for more details on Radio Button

Solution 6 - Android

try to use this

<RadioGroup
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"	   
	android:orientation="horizontal"
>    
	<RadioButton
		android:id="@+id/standard_delivery"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/Standard_delivery"
		android:checked="true"
		android:layout_marginTop="4dp"
		android:layout_marginLeft="15dp"
		android:textSize="12dp"
		android:onClick="onRadioButtonClicked"   
	/>

	<RadioButton
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/Midnight_delivery"
		android:checked="false"
		android:layout_marginRight="15dp"
		android:layout_marginTop="4dp"
		android:textSize="12dp"
		android:onClick="onRadioButtonClicked"
		android:id="@+id/midnight_delivery"
	/>    
</RadioGroup>

this is java class

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.standard_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," standard delivery",Toast.LENGTH_LONG).show();
                    break;
            case R.id.midnight_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," midnight delivery",Toast.LENGTH_LONG).show();
                    break;
        }
    }

Solution 7 - Android

I used the following and it worked for me. I used a boolean validation function where if any Radio Button in a Radio Group is checked, the validation function returns true and a submission is made. if returned false, no submission is made and a toast to "Select Gender" is shown:

  1. MainActivity.java

     public class MainActivity extends AppCompatActivity {
         private RadioGroup genderRadioGroup;
    
         @Override
         protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         
         //Initialize Radio Group And Submit Button
         genderRadioGroup=findViewById(R.id.gender_radiogroup);
         AppCompatButton submit = findViewById(R.id.btnSubmit);
         
         //Submit Radio Group using Submit Button
         submit.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 //Check Gender radio Group For Selected Radio Button
                 if(genderRadioGroup.getCheckedRadioButtonId()==-1){//No Radio Button Is Checked
                     Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG).show();
                 }else{//Radio Button Is Checked
                     RadioButton selectedRadioButton = findViewById(genderRadioGroup.getCheckedRadioButtonId());
                     gender = selectedRadioButton == null ? "" : selectedRadioButton.getText().toString().trim();
                 }
                 //Validate
                 if (validateInputs()) {
                     //code to proceed when Radio button is checked
                 }
             }
         }
         //Validation - No process is initialized if no Radio button is checked
         private boolean validateInputs() {
             if (genderRadioGroup.getCheckedRadioButtonId()==-1) {
                 return false;
             }
             return true;
         }
     }
    
  2. In activity_main.xml:

     <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:orientation="horizontal">
    
         <TextView
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:text="@string/gender"/>
    
         <RadioGroup
                 android:id="@+id/gender_radiogroup"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:orientation="horizontal">
    
             <RadioButton
                     android:id="@+id/male"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="@string/male"/>
    
             <RadioButton
                     android:id="@+id/female"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="@string/female""/>
    
         </RadioGroup>
    
         <android.support.v7.widget.AppCompatButton
             android:id="@+id/btnSubmit"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="@string/submit"/>
    
     </LinearLayout>
    

If no gender radio button is selected, then the code to proceed will not run.

I hope this helps.

Solution 8 - Android

I used the id's of my radiobuttons to compare with the id of the checkedRadioButton that I got using mRadioGroup.getCheckedRadioButtonId()

Here is my code:

mRadioButton1=(RadioButton)findViewById(R.id.first);
mRadioButton2=(RadioButton)findViewById(R.id.second);
mRadioButton3=(RadioButton)findViewById(R.id.third);
mRadioButton4=(RadioButton)findViewById(R.id.fourth);
    
mNextButton=(Button)findViewById(R.id.next_button);

mNextButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int selectedId=mRadioGroup.getCheckedRadioButtonId();

        int n=0;
        if(selectedId==R.id.first){n=1;}

        else if(selectedId==R.id.second){n=2;}

        else if(selectedId==R.id.third){n=3;}

        else if(selectedId==R.id.fourth){n=4;}
        //. . . .
    }

Solution 9 - Android

My answer is according to the documentation, which works fine.

  1. In xml file include android:onClick="onRadioButtonClicked" as shown below:

  2. In Java file implement onRadioButtonClicked method outside onCreate() method as shown below:

    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.b1:
             if (checked)
             {
                 Log.e("b1", "b1" );
                 break;
             }
         case R.id.b2:
             if (checked)
                 break;
     }
    

    }

Solution 10 - Android

mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (mRadioButtonMale.isChecked()) {
                text = "male";
            } else {
                text = "female";
            }
        }
    });

OR

 mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (mRadioButtonMale.isChecked()) { text = "male"; }
            if(mRadioButtonFemale.isChecked()) { text = "female"; }
        }
    });

Solution 11 - Android

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                checkedId = radioGroup.getCheckedRadioButtonId();

                switch (checkedId) {
                    case R.id.expert_rb:
                        // do something
                        break;
                    case R.id.no_expert_rb:
                        // do something else
                        break;
                   
                }
            }
        });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSrihariView Question on Stackoverflow
Solution 1 - AndroidApoorvView Answer on Stackoverflow
Solution 2 - AndroidMehul JoisarView Answer on Stackoverflow
Solution 3 - AndroidRobin EllerkmannView Answer on Stackoverflow
Solution 4 - AndroidMalik ShahbazView Answer on Stackoverflow
Solution 5 - AndroidbalachandarkmView Answer on Stackoverflow
Solution 6 - Androidgaurav guptaView Answer on Stackoverflow
Solution 7 - AndroidprofjackView Answer on Stackoverflow
Solution 8 - AndroidShubhdeep SinghView Answer on Stackoverflow
Solution 9 - AndroidShivam TanejaView Answer on Stackoverflow
Solution 10 - AndroidMuhammad Shoaib MurtazaView Answer on Stackoverflow
Solution 11 - AndroidMGLabsView Answer on Stackoverflow