Android单选按钮未选择给出错误

时间:2014-07-12 10:36:39

标签: android radio-button

我有一个Android Radio按钮,如果未选择单选按钮,我需要显示错误消息。因此,我包含了以下Java代码,但它给出了以下错误。

Logcat ERROR:

07-12 16:00:08.139: E/AndroidRuntime(8282): Uncaught handler: thread main exiting due to uncaught exception
07-12 16:00:08.149: E/AndroidRuntime(8282): java.lang.NullPointerException
07-12 16:00:08.149: E/AndroidRuntime(8282):     at com.example.triviality.QuizActivity$1.onClick(QuizActivity.java:67)

在第67行,下面的句子是

      String answerval = (String) answer.getText();                 

请找到部分Java代码:

butNext.setOnClickListener(new View.OnClickListener() {     
                @Override
                public void onClick(View v) {
                    RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
                    RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
                    String answerval = (String) answer.getText();               
                    if (answerval == "")
                    {   
                        AlertDialog.Builder alertDialog  = new AlertDialog.Builder(QuizActivity.this);
                        alertDialog.setTitle(" ");
                        alertDialog.setIcon(R.drawable.wrong);
                        alertDialog.setMessage("Please select one Option"); 
                        alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int which) {
                            }                   
                            });
                        alertDialog.show();
                    }
                }

1 个答案:

答案 0 :(得分:1)

您希望在未选择RadioButton时显示错误消息。

如果是这种情况,则grp.getCheckedRadioButtonId()将返回-1,因此answer将为null

然后,如果您尝试执行answer.getText(),则会得到NullPointerException,因为您在空对象上调用getText

修改

替换

RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
String answerval = (String) answer.getText();               
if (answerval == "")

if(grp.getCheckedRadioButtonId()==-1)