Android getting value from selected radiobutton

JavaAndroidXml

Java Problem Overview


I have a piece of code with three RadioButtons within a RadioGroup. I want to set an onCheckedListener that will show the value of the RadioButton in a Toast. However what I have gotten so far is not working. How do I get the value of the RadioButton and display it in a Toast? This is my code:

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {

    RadioGroup rg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
        final String value =
            ((RadioButton)findViewById(rg.getCheckedRadioButtonId()))
            .getText().toString();

        rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
        	    Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

XML file:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="152dp" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choose 1" />

         <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choose 2" />

         <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choose 3" />
     </RadioGroup>
 </RelativeLayout>

Java Solutions


Solution 1 - Java

Tested and working. Check this

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
 
public class MyAndroidAppActivity extends Activity {
 
  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button btnDisplay;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
 
	addListenerOnButton();
 
  }
 
  public void addListenerOnButton() {
 
	radioGroup = (RadioGroup) findViewById(R.id.radio);
	btnDisplay = (Button) findViewById(R.id.btnDisplay);
 
	btnDisplay.setOnClickListener(new OnClickListener() {
 
		@Override
		public void onClick(View v) {
 
		        // get selected radio button from radioGroup
			int selectedId = radioGroup.getCheckedRadioButtonId();
 
			// find the radiobutton by returned id
		    radioButton = (RadioButton) findViewById(selectedId);
 
			Toast.makeText(MyAndroidAppActivity.this,
				radioButton.getText(), Toast.LENGTH_SHORT).show();
 
		}
 
	});
 
  }
}

xml

<RadioGroup
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
 
        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />
 
        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />
 
    </RadioGroup>

Solution 2 - Java

In case, if you want to do some job on the selection of one of the radio buttons (without having any additional OK button or something), your code is fine, updated little.

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
		
		rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
		{
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch(checkedId){
					case R.id.radio0:
						// do operations specific to this selection
					    break;
					case R.id.radio1:
						// do operations specific to this selection
					    break;
					case R.id.radio2:
						// do operations specific to this selection
					    break;
				}	
			}
		});
	}
}

Solution 3 - Java

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(RadioGroup group, int checkedId)
       {
           radioButton = (RadioButton) findViewById(checkedId);
           Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
       }
   }
   );

Solution 4 - Java

int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();

Hope this works. You can convert your output to string in the above manner. gender.getCheckedRadioButtonId(); - gender is the id of RadioGroup.

Solution 5 - Java

mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
    }
});

Solution 6 - Java

For anyone who is populating programmatically and looking to get an index, you might notice that the checkedId changes as you return to the activity/fragment and you re-add those radio buttons. One way to get around that is to set a tag with the index:

    for(int i = 0; i < myNames.length; i++) {
        rB = new RadioButton(getContext());
        rB.setText(myNames[i]);
        rB.setTag(i);
        myRadioGroup.addView(rB,i);
    }

Then in your listener:

    myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
            int mySelectedIndex = (int) radioButton.getTag();
        }
    });

Solution 7 - Java

just use getCheckedRadioButtonId() function to determine wether if anything is checked, if -1 is the return value, you can avoid showing toast

Solution 8 - Java

Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            RadioButton rb= (RadioButton) findViewById(checkedId);
            team = rb.getText().toString();
        }
    });

Solution 9 - Java

RadioGroup in XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Java"/>

    </RadioGroup>
</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="100dp"
        android:textSize="18dp"
        android:text="Select Your Course"
        android:textStyle="bold"
        android:id="@+id/txtView"/>
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/rdGroup"
    android:layout_below="@+id/txtView">
    <RadioButton
        android:id="@+id/rdbJava"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Java"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbPython"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Python"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Android"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAngular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="AngularJS"
        android:onClick="onRadioButtonClicked"/>
</RadioGroup>
    <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_below="@+id/rdGroup"
        android:text="Get Course" />
</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    RadioButton android, java, angular, python;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android = (RadioButton)findViewById(R.id.rdbAndroid);
        angular = (RadioButton)findViewById(R.id.rdbAngular);
        java = (RadioButton)findViewById(R.id.rdbJava);
        python = (RadioButton)findViewById(R.id.rdbPython);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "Selected Course: ";
                result+= (android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onRadioButtonClicked(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        String str="";
        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.rdbAndroid:
                if(checked)
                str = "Android Selected";
                break;
            case R.id.rdbAngular:
                if(checked)
                str = "AngularJS Selected";
                break;
            case R.id.rdbJava:
                if(checked)
                str = "Java Selected";
                break;
            case R.id.rdbPython:
                if(checked)
                str = "Python Selected";
                break;
        }
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
    }
}

Solution 10 - Java

Thanks a lot to Chris.

This is my solution:

RadioGroup radgroup_opcionesEventos = null;


 private static String[] arrayEventos = {
            "Congestión", "Derrumbe", "Accidente"
    };
@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        radgroup_opcionesEventos = (RadioGroup)findViewById(R.id.rg_opciones_evento);
        int i=0;//a.new.ln
        for(String evento : arrayEventos) {
            //RadioButton nuevoRadio = crearRadioButton(evento);//a.old.ln
            RadioButton nuevoRadio = crearRadioButton(evento,i);//a.new.ln
            radgroup_opcionesEventos.addView(nuevoRadio,i);
        }

        RadioButton primerRadio = (RadioButton) radgroup_opcionesEventos.getChildAt(0);
        primerRadio.setChecked(true);
}

private RadioButton crearRadioButton(String evento, int n)
    {
        //RadioButton nuevoRadio = new RadioButton(this);//a.old.ln
        RadioButton nuevoRadio = new RadioButton(getApplicationContext());//a.new.ln

        LinearLayout.LayoutParams params = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        nuevoRadio.setLayoutParams(params);
        nuevoRadio.setText(evento);
        nuevoRadio.setTag(evento);
        return nuevoRadio;
    }


@Override
    protected void onResume()
    {
        radgroup_opcionesEventos.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
                //int mySelectedIndex = (int) radioButton.getTag();
                String mySelectedIndex = radioButton.getTag().toString();
            }
        });
        super.onResume();
    }

Solution 11 - Java

I have had problems getting radio buttons id's as well when the RadioButtons are dynamically generated. It does not seem to work if you try to manually set the ID's using RadioButton.setId(). What worked for me was to use View.getChildAt() and View.getParent() in order to iterate through the radio buttons and determine which one was checked. All you need is to first get the RadioGroup via findViewById(R.id.myRadioGroup) and then iterate through it's children. You'll know as you iterate through which button you are on, and you can simply use RadioButton.isChecked() to determine if that is the button that was checked.

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
Questionuser2673161View Question on Stackoverflow
Solution 1 - Javachinna_82View Answer on Stackoverflow
Solution 2 - JavaKapsView Answer on Stackoverflow
Solution 3 - JavaTuruuView Answer on Stackoverflow
Solution 4 - JavaGowthamView Answer on Stackoverflow
Solution 5 - JavaAshish DwivediView Answer on Stackoverflow
Solution 6 - JavaChrisView Answer on Stackoverflow
Solution 7 - JavapailodzeView Answer on Stackoverflow
Solution 8 - Javasaigopi.meView Answer on Stackoverflow
Solution 9 - JavaMr_MoradiView Answer on Stackoverflow
Solution 10 - JavaJonathan Eduardo Tito OntanedaView Answer on Stackoverflow
Solution 11 - JavaA. VinView Answer on Stackoverflow