我有一個Android單選按鈕,如果沒有選中單選按鈕,我需要顯示錯誤消息。因此我包含了下面的Java代碼,但是它給出了下面的錯誤。Android單選按鈕沒有選擇給出錯誤
logcat的錯誤:
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();
}
}
您findViewById代碼必須是外面setOnClickListener之前。 –