jigar
jigar

Reputation: 1591

Radio group not working in android

I ahve made a simple radioButton demo in android.In that i have put a radiogroup with two radio buttons named "male" and "female"...and a button .I want is when one of them pressed the name related to that particular radiobutton should be in toast.I have tried as below thats not working:

Activity.java

package com.example.radiobuttondemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends Activity {
RadioButton rd1,rd2;
Button b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    rd1=(RadioButton)findViewById(R.id.radio0);
    rd2=(RadioButton)findViewById(R.id.radio1);
    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            if(rd1.isChecked()){
                Toast.makeText(getApplicationContext(), "male", 0).show();
            }
            else{
                Toast.makeText(getApplicationContext(), "Female", 0).show();
            }


        }
    });
    }



}

Upvotes: 0

Views: 1612

Answers (4)

Arvis
Arvis

Reputation: 8363

Do the check against RadioButton group itself:

switch (radioGroup.getCheckedRadioButtonId()) {
            case rd1:
                     Toast.makeText(getApplicationContext(), "male", 0).show();
                     break;
            case rd2:
                     Toast.makeText(getApplicationContext(), "Female", 0).show();
                     break;
)

Upvotes: 0

Stephan Branczyk
Stephan Branczyk

Reputation: 9375

Personally, I've always used RadioGroup for my radio buttons. If you didn't use that, how would it know to uncheck one radio button when you checked the other radio button?

See http://www.mkyong.com/android/android-radio-buttons-example/

Now if you're dealing with a normal checkbox, your approach would be fine I suppose. A normal checkbox wouldn't need to know about its siblings.

Upvotes: 0

Romain R
Romain R

Reputation: 41

You must bind your button with the Button object (that you named b) in your MainActivity class. There is an action listener on b, but b is not binded...

Upvotes: 0

Alexis C.
Alexis C.

Reputation: 93842

You forgot to initialize your Button b.

So when you're doing b.setOnClickListener, your program throws a NullPointerException and make your app closed.

Upvotes: 1

Related Questions