2010-07-18 33 views
2

我對Android非常陌生,所以我一直主要從android開發者頁面獲取信息。一切都很好,直到我從警報對話框部分添加了代碼。當我嘗試在最後一行運行它時,它們給出的代碼給我一個錯誤,說我必須初始化對話框,但無論情況如何,我都覺得我得到NullPointerException異常...繼承人我的代碼:難以顯示警告對話框,爲什麼此代碼強制關閉我的應用程序?

protected Dialog onCreateDialog(int id) { 
     Dialog dialog = null; 
     switch(id) { 
     case NAME_MISSING_ID: 
      // do the work to define the Dialog 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setMessage("Proceed without a name?") 
        .setCancelable(false) 
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          MainActivity.this.finish(); 
         } 
        }) 
        .setNegativeButton("No", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dialog.cancel(); 
         } 
        }); 
      AlertDialog alert = builder.create(); 
      break; 
     case HARD_SELECTION_ID: 
      // do the work to define the Dialog 
      AlertDialog.Builder builder2 = new AlertDialog.Builder(this); 
      builder2.setMessage("This is INSANE! Are you sure?") 
        .setCancelable(false) 
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          MainActivity.this.finish(); 
         } 
        }) 
        .setNegativeButton("No", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dialog.cancel(); 
         } 
        }); 
      AlertDialog alert2 = builder2.create(); 
      break; 
     default: 
      dialog = null; 
     } 
     return dialog; 
    } 

如果我沒有在開始時將「dialog」初始化爲「null」,我就無法運行該程序。我甚至沒有試圖做任何瘋狂的事情,任何幫助都會很棒,因爲我在試圖弄清楚這段代碼試圖做什麼時遇到了很多麻煩。

謝謝你們!

+0

你可以發佈應用程序崩潰時的日誌嗎?你可以使用'adb logcat'命令,或者從eclipse打開logcat。 – Cristian 2010-07-18 05:21:33

回答

1

在所有情況下您都返回null - 請參閱對話框變量,它從不會指定值。

你可能想改變這些行:
AlertDialog alert = builder.create();
AlertDialog alert2 = builder2.create();

這樣:
dialog = builder.create();
dialog = builder2.create();

而且最好給我們完整的堆棧跟蹤下一次。

+0

您可以在開始時初始化AlertDialog.Builder構建器,而不是爲每個案例創建它。 – 2010-07-18 05:25:14

+0

哦,我想這是有道理的,我錯過了改變,當我將代碼的警報段添加到原始對話框代碼,我會去嘗試,但你是什麼意思的「全堆棧跟蹤」?對不起,我從未發佈過任何內容...... – Aaron 2010-07-18 05:25:48

1

問題是你沒有返回對話框...... createDialog總是返回null。

,而不是AlertDialog alert = builder.create();你應該

return builder.create(); 

這兩種情況下,很明顯。

+0

工作正常!感謝很多人,我坐在這裏,盯着這個代碼兩個小時哈哈......我真的很感謝幫助,而且很快! – Aaron 2010-07-18 05:29:56

相關問題