2012-04-25 45 views
1

內創建警報對話框我想創建一個從處理器女巫的警告對話框被暗示當一個線程終止,這是我的代碼巫婆導致處理器

android.view.WindowManager $ BadTokenException:無法添加窗口 - 令牌null不是一個應用程序

Handler handler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 

     if (dialog != null) 
     { 
      dialog.dismiss(); 
      dialog = null; 
     } 

     switch (serverResponseCode) 
     { 
     case 200: 
     { 
      AlertDialog alertDialog; 
      alertDialog = new AlertDialog.Builder(getApplicationContext()).create(); 
      alertDialog.setTitle("Super :)"); 
      alertDialog.setMessage("Poza a fost trimisa cu success."); 
      alertDialog.setButton("Ok", new DialogInterface.OnClickListener() { 

        public void onClick(DialogInterface dialog, int id) { 

        finish(); 

       } }); 
      alertDialog.show(); 
      serverResponseCode = -1; 

      break; 
     } 
     default: 
     { 
      AlertDialog alertDialog; 
      alertDialog = new AlertDialog.Builder(getApplicationContext()).create(); 
      alertDialog.setTitle("Eroare :("); 
      alertDialog.setMessage("Eroare la trimiterea pozei."); 
      alertDialog.setButton("Ok", new DialogInterface.OnClickListener() { 

        public void onClick(DialogInterface dialog, int id) { 

        finish(); 

       } }); 
      alertDialog.show(); 

      break; 
     } 
     } 


     } 
    }; 

回答

3

不能使用應用程序上下文來創建對話框。改爲使用活動上下文 。

另外,創建對話框的這種方式必然會在以後造成問題,特別是如果活動因任何原因而重新啓動時。您應該用對話的片段,或管理對話框(活動的showDialog()法)

1

我相信你在做Android的內部WebService的請求/響應,那麼我建議你實現AsyncTask這被稱爲Painless Threading在android系統,因爲你不需要麻煩線程管理。

僅供參考,在doInBackground()之內 - 編寫網絡調用邏輯,在onPostExecute()之內 - 顯示您要顯示的警報對話框。

+2

太棒了!感到尷尬,因爲這個答案不被接受。 – 2012-04-27 09:00:27

+0

請注意,答案並不是那麼簡單。 Android的Activity生命週期會導致AsyncTask問題 - 請參閱http://stackoverflow.com/questions/3357477/is-asynctask-really-conceptually-flawed-or-am-i-just-missing-something以獲取更多詳細信息。 – hrnt 2012-05-08 11:29:08

4

問題可能是getApplicationContext()不是您的活動上下文。

alertDialog = new AlertDialog.Builder(getApplicationContext()).create(); 
    //should be change to 
    alertDialog = new AlertDialog.Builder(YourActivity.this).create();