2014-07-12 38 views
0

我有一個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(); 
        } 
       } 
+0

您findViewById代碼必須是外面setOnClickListener之前。 –

回答

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) 
+0

我可以在那個地方放什麼代碼 – user3326228

+0

@ user3326228檢查編輯。 – Apoorv