无法按任何RadioButton

时间:2017-02-26 14:28:19

标签: java android nullpointerexception

我无法使代码正常运行。它可以启动,但我不能选择任何东西。 因为我添加了setOnClikListener方法,所以就是这样。我还尝试了setOnCheckedChangeListener

在我实施之前

btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(rg1.getCheckedRadioButtonId() == R.id.radioButton2 && rg2.getCheckedRadioButtonId() == R.id.radioButton4){
                tv.setText(R.string.Good_answer);}
            else{
                tv.setText(R.string.Wrong_answer);}
        }
    });

这段代码一切正常。

RadioButton radioButton2;
RadioButton radioButton4;
RadioGroup rg1,rg2;
TextView tv;
RadioButton btn;

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

public void OnRadioButtonClick(View view) {
    boolean checked = ((RadioButton) view).isChecked();

    radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
    radioButton4 = (RadioButton) findViewById(R.id.radioButton4);
    switch (view.getId()) {
        case R.id.radioButton1:

            Toast.makeText(MainActivity.this, "1 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton2:

            Toast.makeText(MainActivity.this, "2 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton3:

            Toast.makeText(MainActivity.this, "3 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;
        case R.id.radioButton4:

            Toast.makeText(MainActivity.this, "4 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton5:

            Toast.makeText(MainActivity.this, "5 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton6:

            Toast.makeText(MainActivity.this, "6 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;
    }

在控制台中获取此内容

> $ adb shell am start -n "make.myapplication1/make.myapplication1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: make.myapplication1.test | make.myapplication1
Connecting to make.myapplication1
I/art: Late-enabling -Xcheck:jni
W/art: Unexpected CPU variant for X86 using defaults: x86
W/ActivityThread: Application make.myapplication1 is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1364)
W/System: ClassLoader referenced unknown path: /data/app/make.myapplication1-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
E/libEGL: load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library "/system/lib/egl/libGLES_emulation.so" not found
D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so

          [ 02-26 09:34:50.095  2037: 2059 D/         ]
          HostConnection::get() New Host Connection established 0xe7e8e4b0, tid 2059
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
I/Choreographer: Skipped 68 frames!  The application may be doing too much work on its main thread.
Connected to the target VM, address: 'localhost:8625', transport: 'socket'
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: make.myapplication1, PID: 2037
                  java.lang.IllegalStateException: Could not execute method for android:onClick
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                      at android.view.View.performClick(View.java:5609)
                      at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                      at android.view.View$PerformClick.run(View.java:22259)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.reflect.InvocationTargetException
                      at java.lang.reflect.Method.invoke(Native Method)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                      at android.view.View.performClick(View.java:5609) 
                      at android.widget.CompoundButton.performClick(CompoundButton.java:122) 
                      at android.view.View$PerformClick.run(View.java:22259) 
                      at android.os.Handler.handleCallback(Handler.java:751) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6077) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CompoundButton.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
                      at make.myapplication1.MainActivity.OnRadioButtonClick(MainActivity.java:68)
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                      at android.view.View.performClick(View.java:5609) 
                      at android.widget.CompoundButton.performClick(CompoundButton.java:122) 
                      at android.view.View$PerformClick.run(View.java:22259) 
                      at android.os.Handler.handleCallback(Handler.java:751) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6077) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

最新版本。 Stil不能按任何rb。

public class MainActivity extends AppCompatActivity {


private Boolean[] answer = new Boolean[2];
private Boolean[] checkedAnswer = new Boolean[2];


RadioButton radioButton2;
RadioButton radioButton4;
RadioGroup rg1, rg2;
TextView tv;
RadioButton btn;

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

public void OnRadioButtonClick(View view) {
    final boolean checked = ((RadioButton) view).isChecked();

    radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
    radioButton4 = (RadioButton) findViewById(R.id.radioButton4);
    switch (view.getId()) {
        case R.id.radioButton1:

            Toast.makeText(MainActivity.this, "1 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton2:

            Toast.makeText(MainActivity.this, "2 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton3:

            Toast.makeText(MainActivity.this, "3 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;
        case R.id.radioButton4:

            Toast.makeText(MainActivity.this, "4 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton5:

            Toast.makeText(MainActivity.this, "5 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;

        case R.id.radioButton6:

            Toast.makeText(MainActivity.this, "6 is selected" + String.valueOf(checked),
                    Toast.LENGTH_SHORT).show();
            break;
    }
    rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.radioButton2) {
                checkedAnswer[0] = true;
                answer[0] = true;
            } else {
                checkedAnswer[0] = true;
                answer[0] = false;
            }
        }
    });
    rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.radioButton4) {
                checkedAnswer[1] = true;
                answer[1] = true;
            } else {
                checkedAnswer[1] = true;
                answer[1] = false;
            }
        }
    });

    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            boolean check = true;
            boolean correct = true;

            for (boolean radioChecked : checkedAnswer)
                check = check && radioChecked;
            if (check) {
                for (boolean radioAnswer : answer)
                    correct = correct && radioAnswer;
                if (correct)
                    tv.setText(R.string.Good_answer);
                else
                    tv.setText(R.string.Wrong_answer);
            }
        }
    });
}

}

XML

<RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Radio_Group">

        <RadioButton
            android:text="Option1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton1"
            android:layout_weight="1"
            android:onClick="OnRadioButtonClick" />

        <RadioButton
            android:text="Option2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton2"
            android:onClick="OnRadioButtonClick" />

        <RadioButton
            android:text="Option3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton3"
            android:layout_weight="1"
            android:onClick="OnRadioButtonClick" />


    </RadioGroup>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Radio_Group1"
        android:layout_below="@+id/Radio_Group"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="68dp">

        <RadioButton
            android:text="Option4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton4"
            android:onClick="OnRadioButtonClick" />

        <RadioButton
            android:text="Option5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton5"
            android:layout_weight="1"
            android:onClick="OnRadioButtonClick" />

        <RadioButton
            android:text="Option6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButton6"
            android:layout_weight="1"
            android:onClick="OnRadioButtonClick" />


    </RadioGroup>

</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

情景1:

尝试将OnCheckedChangeListener()设置为radioGroups并检查其中选择了哪个单选按钮。

例如:

假设你的RadioButtons radioButton1,radioButton2,radioButton3和radioButton4都在你的RadioGroup rg1里面。

XML文件:

<RadioGroup
    android:id="@+id/rg1"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RadioButton
        android:id="@+id/radioButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RadioButton
        android:id="@+id/radioButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RadioGroup>

JAVA文件:

RadioGroup rg1 = (RadioGroup) findViewById(R.id.rg1);

rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        ////////////////////////////////////////////////////////////////////////////////////
        // the onCheckedChanged() function takes in two arguments the second of which is
        // the Id of the radio button which ws checked
        // Inside is an if condition checking the Id of the RadioButton selected and depending
        // on the Id we are setting value to the textViews as per your code.
        ////////////////////////////////////////////////////////////////////////////////////
        if ((checkedId == R.id.radioButton1) || (checkedId == R.id.radioButton2)) {
            tv.setText(R.string.Good_answer);
        } else {
            tv.setText(R.string.Wrong_answer);
        }
    }
});

情景2:

但是,如果您有两个单独的RadioGroups,每个RadioGroups中有两个RadioButtons,并想检查每个组中是否选择了正确的单选按钮,您可以这样做:

JAVA文件:

boolean[] answer = new boolean[2];
boolean[] checked = new boolean[2];

checked[0] = false;
checked[1] = false;

RadioGroup rg1 = (RadioGroup) findViewById(R.id.rg1);
// radioButton1 and radioButton2 are in rg1

RadioGroup rg2 = (RadioGroup) findViewById(R.id.rg1);
// radioButton3 and radioButton4 are in rg1

rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        if (checkedId == R.id.radioButton1) {
            checked[0] = true;
            answer[0] = false;
            checkAnswer();
        } else {
            checked[0] = true;
            answer[0] = true; 
            checkAnswer();           
        }
    }
});

rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        if (checkedId == R.id.radioButton3) {
            checked[1] = true;
            answer[1] = false;
            checkAnswer();
        } else {
            checked[1] = true;
            answer[1] = true;
            checkAnswer();
        }
    }
});

checkAnswer():

public void checkAnswer(){
    if(checked[0] && checked[1]){
        if(answer[0] && answer[1])
            tv.setText(R.string.Good_answer);
        else
            tv.setText(R.string.Wrong_answer);
    }

我使用了两个布尔数组:

1)检查每个RadioGroup中是否有一个RadioButton被选中(选中[])

2)检查每个RadioGroup中是否选中了正确的选项(answer [])

这是我能从你提供的代码中找到的全部内容。我希望这就是你要找的东西。另外,这是我第一次在这里发帖。如果有什么事情,请纠正我。

修改

示例应用

我制作了一个活动应用程序,其中包含两个问题,每个问题有三个选项这是文件。

<强> activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    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">

    <RadioGroup
        android:id="@+id/rg1"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:textColor="@android:color/black"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Question 1"/>

        <RadioButton
            android:text="Correct Option"
            android:id="@+id/radioButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


        <RadioButton
            android:text="Wrong Option"
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <RadioButton
            android:text="Wrong Option"
            android:id="@+id/radioButton3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RadioGroup>

    <RadioGroup
        android:layout_marginTop="16dp"
        android:layout_below="@+id/rg1"
        android:id="@+id/rg2"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:textColor="@android:color/black"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Question 2"/>


        <RadioButton
            android:text="Wrong Option"
            android:id="@+id/radioButton4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <RadioButton
            android:text="Correct Option"
            android:id="@+id/radioButton5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


        <RadioButton
            android:text="Wrong Option"
            android:id="@+id/radioButton6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RadioGroup>

    <TextView
        android:id="@+id/textViewAnswer"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textAlignment="center"
        android:layout_above="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_marginTop="8dp"
        android:id="@+id/button"
        android:text="check answers"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

<强> MainActivity.java

如果您有多个问题而不是在每个组上分配设置OnCheckedChangeListener,您可以让MainActivity实现RadioGroup.OnCheckedChangeListener来处理多个RadioGroup。

public class MainActivity extends AppCompatActivity{

    // Initialize to the number of question
    private static int NUMBER_OF_QUESTIONS = 2;
    private Boolean[] answer = new Boolean[NUMBER_OF_QUESTIONS];
    private Boolean[] checked = new Boolean[NUMBER_OF_QUESTIONS];

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

        RadioGroup rg1 = (RadioGroup) findViewById(R.id.rg1);
        RadioGroup rg2 = (RadioGroup) findViewById(R.id.rg2);
        final TextView tv = (TextView) findViewById(R.id.textViewAnswer);
        Button mButton = (Button) findViewById(R.id.button);

        // Listener for question1
        // Let us suppose A is the correct answer (R.id.radioButton1)
        rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radioButton1) {
                    checked[0] = true;
                    answer[0] = true;
                } else {
                    checked[0] = true;
                    answer[0] = false;
                }
            }
        });

        // Listener for question1
        // Let us suppose B is the correct answer (R.id.radioButton5)
        rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radioButton5) {
                    checked[1] = true;
                    answer[1] = true;
                } else {
                    checked[1] = true;
                    answer[1] = false;
                }
            }
        });

        // Listener for button to check answers
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean check = true;
                boolean correct = true;
                // To check if all questions have been answered
                for (boolean radioChecked : checked)
                    check = check && radioChecked;
                if (check) {

                    // To check if all questions have been answered correctly
                    for (boolean radioAnswer : answer)
                        correct = correct && radioAnswer;
                    if (correct)
                        tv.setText(R.string.Good_answer);
                    else
                        tv.setText(R.string.Wrong_answer);

                }
                else
                    tv.setText("Answer all questions");
            }
        });
    }
}

我希望这最终能解决你的问题。 :)

<强>截图:

enter image description here

enter image description here