14

I have some problem with radio group, I am new to Android development so I don't have much idea to how can handle it.This is form which has some input filed and radio group for choosing gender and save button. but I don't know where can I exactly put my radiogroup setoncheakchangelistener? so it gives me errors.

MAIN ACTIVITY :

package com.dietandroidproject;

import Databasedata.Person;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender);

    genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()            {

        @Override
        public void onCheckedChanged(RadioGroup arg0, int selectedId) {
            selectedId=genderselected.getCheckedRadioButtonId();
            RadioButton genderchoosed = (RadioButton) findViewById(selectedId);
            String gender = genderchoosed.getText().toString();

        }
     });

    Button saveinformation = (Button) findViewById(R.id.saveinformation);
    saveinformation.setOnClickListener(new View.OnClickListener() {

        EditText weighttext = (EditText) findViewById(R.id.weighttext);
        EditText heighttext = (EditText) findViewById(R.id.heighttext);
        EditText usernametext = (EditText) findViewById(R.id.usernametext);
        EditText agetext = (EditText) findViewById(R.id.agetext);
        Spinner activitytext = (Spinner) findViewById(R.id.chooseactivity);
        Button saveinformation = (Button) findViewById(R.id.saveinformation);
        String pa = activitytext.getSelectedItem().toString();
         @Override
        public void onClick(View v) {

            int weight = (int) Float.parseFloat(weighttext.getText()
                    .toString());
            int height = (int) Float.parseFloat(heighttext.getText()
                    .toString());
            String username = usernametext.getText().toString();
            int age = (int) Float.parseFloat(agetext.getText().toString());
            TextView genderchoosed = (TextView) findViewById(genderselected
                    .getCheckedRadioButtonId());
            String gender = genderchoosed.getText().toString();
            String pa = activitytext.getSelectedItem().toString();

       //BMI==========================================================
            int Bmivalue = calculateBMI(weight, height);
            String bmiInterpretation = interpretBMI(Bmivalue);
            float idealweight = idealweight(weight, height, gender, pa, age);
            double dailycalories=dailycalories(weight,height,gender,pa,age);

         //insert data in to db===================================================
           Person person = new Person();
            person.setUsername(username);
            person.setHeight(height);
            person.setWeight(weight);
            person.setAge(age);
            person.setGender(gender);
            person.setPa(pa);
            person.setBmivalue(Bmivalue);
            person.setBmiInterpretation(bmiInterpretation);
            person.setIdealweight(idealweight);
            person.setDailycalories(dailycalories);
            Databasedata.DatabaseAdapter dbAdapter = new Databasedata.DatabaseAdapter(
                    MainActivity.this);
            dbAdapter.insertPerson(person);

            Toast.makeText(getApplicationContext(),
                    Bmivalue + "and you are" + bmiInterpretation,
                    Toast.LENGTH_LONG).show();

           }
         });
        }
        //BMI FUNCTION===============================================
        private int calculateBMI(int weight, int height) {

           return (int) (weight / (height * height));
        };

        private String interpretBMI(int Bmivalue) {

         if (Bmivalue < 18.5) {
          return "Underweight";
         } else if (Bmivalue < 25) {
           return "Normal";
         } else if (Bmivalue < 30) {
           return "Overweight";
         } else {
           return "Obese";
         }
        }
         //IDEAL WEIGHT========================================

private float idealweight(int weight, int height, String gender, String pa,
        int age) {
    float x = (float) 0.0;
    int bmi;

    bmi = idealbmi(age);
    x = bmi * (height * height);
    return x;

  }

   public int idealbmi(int age) {
    int bmi = 0;
    if (age > 17 && age <= 19) {
        bmi = 21;
    }
    if (age > 19 && age <= 24) {
        bmi = 22;
    }
    if (age > 24 && age <= 34) {
        bmi = 23;
    }
    if (age > 34 && age <= 44) {
        bmi = 24;
    }
    if (age > 44 && age <= 54) {
        bmi = 25;
    }
    if (age > 54 && age <= 64) {
        bmi = 26;
    }
    if (age > 64) {
        bmi = 27;
    }

    return bmi;
    }
    //DAILY CALORIES===============================================
    public double suitablepa(String pa) {
    double suitablepa = 0;
    if (pa.equals("Highly active")) {
        suitablepa =  1.48;
    }
    if (pa.equals("Active")) {
        suitablepa =  1.25;
    }
    if (pa.equals("Low activity")) {
        suitablepa =  1.11;
    }
    if (pa.equals("Sedentary")) {
        suitablepa =  1;
    }
    return suitablepa;

  }

  private double dailycalories(int weight, int height, String gender,
        String pa, int age) {
    double dailycalori = 0;
    double i;
    double j;
    double h;
    double k;
    if(gender.equals("femaleselected")){

        i=9.36*weight;
        j=726*height;
        h=suitablepa(pa)*(i+j);
        k=6.91*age;
        dailycalori=354-k+h;

    }else if(gender.equals("maleselected")){

        i=15.91*weight;
        j=539.6*height;
        h=suitablepa(pa)*(i+j);
        k=9.53*age;
        dailycalori=662-k+h;
    }


    return dailycalori;
}
}

XML CODES

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/backgroundmain"
android:orientation="vertical" >

<RelativeLayout
    android:id="@+id/personinformation"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1.98" >

    <EditText
        android:id="@+id/heighttext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/usernametext"
        android:layout_below="@+id/usernametext"
        android:ems="10"
        android:hint="Enter Your Height" >
    </EditText>

    <EditText
        android:id="@+id/usernametext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="Enter Username" />

    <EditText
        android:id="@+id/weighttext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/heighttext"
        android:layout_below="@+id/heighttext"
        android:ems="10"
        android:hint="Enter Your Weight" />

    <EditText
        android:id="@+id/agetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/weighttext"
        android:layout_below="@+id/weighttext"
        android:ems="10"
        android:hint="Enter Your Age" >

        <requestFocus />
    </EditText>

</RelativeLayout>

<View
    android:layout_width="250dp"
    android:layout_height="1dip"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:background="#aaa" />

<RelativeLayout
    android:id="@+id/choosegender"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.78" >

    <TextView
        android:id="@+id/choosefemaleormale"
        android:layout_width="match_parent"
        android:layout_height="30dip"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dip"
        android:gravity="center"
        android:text="Gender : "
        android:textAlignment="center"
        android:textColor="#555"
        android:textSize="19sp" />

    <RadioGroup
        android:id="@+id/selectgender"
        android:layout_width="220dip"
        android:layout_height="wrap_content"
        android:layout_below="@+id/choosefemaleormale"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/femaleselected"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:layout_weight="1"
            android:checked="true"
            android:text="female"
            android:onClick="onRadioButtonClicked"
             />

        <RadioButton
            android:id="@+id/maleselected"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_weight="1"
            android:text="male"
            android:onClick="onRadioButtonClicked" />
    </RadioGroup>
</RelativeLayout>
    <View
    android:layout_width="250dp"
    android:layout_height="1dip"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:background="#aaa" />
<RelativeLayout
    android:id="@+id/choosepa"
    android:layout_width="250dip"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_gravity="center" >

    <Spinner
        android:id="@+id/chooseactivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:entries="@array/activityitems"
        android:gravity="center"
        android:prompt="@string/level_of_activity" />

</RelativeLayout>

<Button
    android:layout_width="90dp"
    android:layout_height="0dp"
    android:layout_gravity="right"
    android:layout_marginBottom="10dip"
    android:layout_marginRight="20dp"
    android:layout_weight="0.46"
    android:background="@drawable/recent_foods_depressed"
    android:hint="save"
    android:text="save"
    android:textColor="#fff"
    android:textSize="20sp"
    android:textStyle="bold" 
    android:onClick="saveinformation"
    android:id="@+id/saveinformation"/>

 </LinearLayout>
mkafiyan
  • 944
  • 2
  • 9
  • 31
  • 1
    What error do you get? – Srijith Aug 03 '14 at 06:21
  • @Sree14 fatal exception :main `08-03 06:22:57.169: E/AndroidRuntime(1188): java.lang.IllegalStateException: Could not find a method onRadioButtonClicked(View) in the activity class com.dietandroidproject.MainActivity for onClick handler on view class android.widget.RadioButton with id 'maleselected' ` – mkafiyan Aug 03 '14 at 06:24
  • Have you tried using `setOnCheckedChangeListener()` for radio buttons instead of radiogroups. Or else you can also try `android:onClick` for your radio buttons in your xml. http://developer.android.com/guide/topics/ui/controls/radiobutton.html – Srijith Aug 03 '14 at 06:27
  • ok got it. please remove your androi:onclick from xml. – Srijith Aug 03 '14 at 06:30
  • @Sree14 yes at first I tried using `setOnCheckedChangeListener()` for radio button, and also I tried [http://www.mkyong.com/android/android-radio-buttons-example/] but no answer. – mkafiyan Aug 03 '14 at 06:31
  • @Sree14 sorry I have another question,I wrote `String gender = genderchoosed.getText().toString();` in `onCheckedChanged` so I can use it as gender type in `float idealweight = idealweight(weight, height, gender, pa, age);` and others function but I cant access gender from my function. how can I solve it? – mkafiyan Aug 03 '14 at 06:59
  • Before onCreate declare your string: `String gender;`. And in your `onCheckedChanged()` just define it as `gender = genderchoosed.getText().toString();`. Now you can access it. – Srijith Aug 03 '14 at 07:04
  • @Sree14 sorry about streing gender which u said I have to declare before onCreat I have problem with this case because I have to get the value of gender from `gender = genderchoosed.getText().toString();` and then use it in my function.is there any way which can I solve this problem. – mkafiyan Aug 03 '14 at 16:15
  • Call that `idealweight` method from your radiogroups `onCheckedChanged` method passing in the parameter as `gender`. – Srijith Aug 04 '14 at 05:08
  • @Sree14 u mean that I have to call all method which use gender in `onCheckedChanged`?? if i do as u said, when click on the button "save" because `onclick` dosent access to variable in `nCheckedChanged` so cant insert them in db?right???!!! – mkafiyan Aug 04 '14 at 05:43
  • Ok if many methods want to refer `gender`, you can do the following: You can use getter and setter methods. You have to call the setter method in your `onCheckedChanged` method passing the `gender` as parameter. And those who want to refer the `gender` can simply call the getter methods. Please search about getter and setter methods if you dont know. – Srijith Aug 04 '14 at 07:31
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58593/discussion-between-mimi-and-sree14). – mkafiyan Aug 04 '14 at 07:37

6 Answers6

21
 radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
            RadioButton rb=(RadioButton)findViewById(checkedId);
            Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
        }
    });
Ali
  • 1,265
  • 14
  • 18
  • can u help me with another question? – mkafiyan Oct 28 '14 at 21:22
  • sure please post your question here in the comments box or at stackoverflow – Ali Oct 30 '14 at 08:25
  • I have some problem with changing text color of action bar u can find more information here http://stackoverflow.com/questions/26617694/change-title-text-color-of-action-bar.thank u – mkafiyan Oct 30 '14 at 08:38
11
RadioGroup yourRadioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
        yourRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                switch(checkedId)
                {
                case R.id.radio0:
                    // TODO Something
                    break;
                case R.id.radio1:
                    // TODO Something
                    break;
                case R.id.radio2:
                    // TODO Something
                    break;
                }
            }
        });

Or, if you prefer:

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

                if(idRadioButtonChosen > 0){

                    radioButtonChosen = (RadioButton) findViewById(idRadioButtonChosen);
                    textViewOnclick.setText(radioButtonChosen.getText());

                }


            }
        });
Thiago Araújo
  • 800
  • 9
  • 8
6

The thing is that your radio buttons trying to refer the onRadioButtonClicked method in your main activity. But you didnt specify that method. Remember, if you're using android:onClick you should not use setOnCheckedChangeListener in your Main activity and vice versa.

Srijith
  • 1,695
  • 17
  • 29
5

In kotlin You can use bellow like..

  radioGroup.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { group, checkedId ->

          val radio:RadioButton = group.findViewById(checkedId)
          Log.e("selectedtext-->",radio.text.toString())

  })

Or

radioGroup.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { group, checkedId ->

         var selectedId = rg.checkedRadioButtonId
         val radio:RadioButton = group.findViewById(selectedId)
            Log.e("selectedtext-->",radio.text.toString())

   })
Enamul Haque
  • 4,789
  • 1
  • 37
  • 50
1

You can use this sample in kotlin:

radioGroup.setOnCheckedChangeListener { _, checkedId ->
        when (checkedId) {
            R.id.radioButton1 -> {

            }
            R.id.radioButton2 -> {

            }
        }
    }
bebosh
  • 806
  • 10
  • 25
-1

this code for radio button not working with radio group

 radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    
      }
    });
sarjeet singh
  • 461
  • 4
  • 10
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P May 23 '22 at 17:29