2011-08-30 42 views
1

我有一個AlertDialog,由於某種奇怪的原因,無法訪問最終的int deptID。 當將值傳遞給ConfirmRemoval函數時,該值是正確的,但是當我輸入對話框的onClick事件時,最終的int值是未定義的!Android對話框無法'查看'最終/全局變量

我甚至試圖改變這個全局變量,但仍然沒有運氣。 有人知道發生了什麼事嗎?

@Override 
public void onCreate(Bundle icicle){ 
    super.onCreate(icicle); 

    this.setContentView(R.layout.generic_list); 
    Bundle extras = getIntent().getExtras(); 
    if (extras == null) {return;} 
    this.getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

     public boolean onItemLongClick(AdapterView<?> adv, View v, 
       int pos, long id) { 
      Cursor cursor = (Cursor)adv.getItemAtPosition(pos); 
      int deptID = cursor.getInt(cursor.getColumnIndex("DeptID")); 
      ConfirmRemoval(deptID); 
      return true; //NOTE! If returning false, the itemClick event will fire 
     } 
    }); 
} 

private void ConfirmRemoval(final int deptID){ 
     AlertDialog.Builder bld = new AlertDialog.Builder(this); 
     bld.setCancelable(false); 
     bld.setTitle(R.string.deptRemove); 
     bld.setMessage(R.string.deptRemoveMsg); 
     bld.setPositiveButton("OK", new AlertDialog.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 

       Dept.RemoveDept(deptID); 
       dialog.dismiss(); 
       GetDepartments(); 
      } 


     }); 
     bld.setNegativeButton("Cancel", new AlertDialog.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 
     AlertDialog alert = bld.create(); 
     alert.show(); 
} 

感謝, Runey

回答

0

而不是

Dept.RemoveDept(deptID)

int deptIDlocal = deptID; Dept.RemoveDept(deptIDlocal)

+0

嘿米哈伊爾,感謝您的評論。問題是,在調試時,deptID獲取一個值(比如5988),但是當我在AlertDialog.onClick事件中調試時,deptID根本沒有任何值??? –

+0

Found錯誤! 事實證明,有一個錯誤 Dept.RemoveDept(deptID) 而不是deptID本身。不知道爲什麼調試器不顯示deptID的值,但顯然是正確的值。仍然有傳遞給函數 奇怪 無論如何,感謝您的意見,夥計們 –

+0

反正我沒有看到它在調試器太...但看看我的其他answear,你可能會喜歡它: ) – mihail

0

嘗試

final int deptID = cursor.getInt(cursor.getColumnIndex("DeptID")); 
+0

嘿格奧爾基,感謝您的建議。試過了。它雖然沒有工作。 :( –

1

好吧,你必須寫自己的OnClickListener - 是這樣的:

public static class processAlert implements DialogInterface.OnClickListener { 
    int deptID; 
    processAlert(int _id){ 
     deptID = _id; 
    } 
    public void onClick(DialogInterface dialog, int which) { 
     Dept.RemoveDept(deptID); 
      dialog.dismiss(); 
      GetDepartments(); 
    } 
} 

,當你創建你的對話

bld.setPositiveButton("OK",new processAlert(deptID))