2011-03-03 28 views
9

Tôi đang sử dụng đoạn mã sau cho menu ngữ cảnh và sau đó nếu người dùng chọn xóa, một hộp thoại massage sẽ xuất hiện.

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; 
} 

Nhưng ngay sau khi tôi chọn xóa, nó sẽ đưa ra lỗi sau.

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

Sự cố trong mã của tôi là gì?

Trả lời

6

Nó phải là AlertDialog.Builder builder = new AlertDialog.Builder (this.getParent());

Do hoạt động ở trong trạng thái hoạt động trong một tabactivity khác.

28

Tôi tin rằng vấn đề có thể được đặt trên dòng này:

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

Hãy thử thay đổi nó để:

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

Thay MyActivityName với tên hoạt động của bạn.

Điều đó có khắc phục được lỗi không?

+0

Sửa lỗi cho tôi! Cảm ơn :) –

6

Tôi đã gặp lỗi tương tự. tôi đã thay đổi

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

để

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

của nó làm việc tốt ngay bây giờ. Cảm ơn.

Các vấn đề liên quan