2011-03-03 78 views
9

我使用下面的代碼作爲上下文菜單,然後如果用戶選擇刪除,將出現對話框按鈕。

infos.setOnCreateContextMenuListener(new OnCreateContextMenuListener(){ 
      //@Override 
      public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { 
       menu.setHeaderTitle("Context Menu"); 
       menu.add(0, CONTEXT_EDIT, 0, "Edit Item"); 
       menu.add(0, CONTEXT_DELETE, 1, "Delete Item"); 
      } 
}); 

public boolean onContextItemSelected(MenuItem item) { 

     AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); 
     final Long _id = menuInfo.id; 
     //selected_row = menuInfo.position; 

     // To get the id of the clicked item in the list use menuInfo.id 
     switch (item.getItemId()) { 
      case CONTEXT_EDIT: 
       addEditRes(_id); 
       break; 
      case CONTEXT_DELETE: 
       AlertDialog.Builder builder = new AlertDialog.Builder(this); 
       builder.setMessage("Are you sure you want to delete?") 
         .setCancelable(false) 
         .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           infoDataHelper.deleteRes(_id); 
           model = infoDataHelper.getCursor(addType); 
           adapter.changeCursor(model); 
          } 
         }) 
         .setNegativeButton("No", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           dialog.cancel(); 
          } 
         }); 
       AlertDialog alert = builder.create(); 
       alert.show(); 
       break; 
      default: 
       return super.onContextItemSelected(item); 

     } 
     adapter.notifyDataSetChanged(); 
     return true; 
} 

但是,儘快我選擇刪除,它給出了以下錯誤。

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 

我的代碼有什麼問題?

回答

6

它應該是 AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());

因爲該活動是在另一個tabactivity內的tabactivity。

28

我認爲這個問題可能是在這條線:

AlertDialog.Builder builder = new AlertDialog.Builder(this); 

嘗試將其改爲:

AlertDialog.Builder builder = new AlertDialog.Builder(MyActivityName.this); 

與活動的名稱替換MyActivityName。

這是否解決了錯誤?

+0

修復了我的問題!謝謝 :) – 2012-11-18 09:25:32

6

我得到了同樣的錯誤。 我改變

AlertDialog.Builder builder = new AlertDialog.Builder(this); 

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 

它現在工作的罰款。謝謝。