Question

I have two RadioButton in a RadioGroup:

<RadioGroup
    android:id="@+id/rgTripType"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="4" >

    <RadioButton
        android:id="@+id/rbOneWay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="One Way" />

    <RadioButton
        android:id="@+id/rbRound"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Round" />
</RadioGroup>

I am calling the RadioGroup in my Java file as:

    final RadioGroup rgTypeOfTrip = (RadioGroup) findViewById(R.id.rgTripType);

        btnCalc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                  Toast.makeText(MainActivity.this, CALL FUNCTION GETINDEX() to get value, Toast.LENGTH_SHORT).show();
        });

        rgTypeOfTrip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub

                // Method 1
                int pos=rgTypeOfTrip.indexOfChild(findViewById(checkedId));
                    getIndex(pos);
                Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();
            }
        });

public int getIndex(int k) {
    return k;
}

What it is supposed to do is display a Toast with the index of the radio button within the radio group. Instead, it causes my program to crash. Any idea how to resolve it?

UPDATE: The index issue is solved.

Issue: How can I use the index value (POS) in the btnClick function?

Was it helpful?

Solution

It crashes because pos is an integer change. If you pass an int value as second paramter you are asking android to look for a String with id the int you provide. If it does not exists the ResourcesNotFoundException will be thrown

Toast.makeText(MainActivity.this, pos, Toast.LENGTH_SHORT).show();

with

 Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();

OTHER TIPS

There are different way .. I used this way

        RadioGroup radiogroup = (RadioGroup) findViewById(R.id.groupid);
    Button bt = (Button) findViewById(R.id.btnDisplay);

    bt.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // get selected radio button from radioGroup
            int selectedId = radiogroup.getCheckedRadioButtonId();
            switch (selectedId) {

                case R.id.radio_button1:
                 // do something..
                    break;
                case R.id.radio_button2:
                  // do something..
                    break;

            }


        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top