2012-05-30 209 views
2

我在開發的應用程序中遇到了一些問題。 因此,我所有的表都有用於主鍵的_id字段,並且我使用SimpleCursorAdapter將它們綁定到ListViews和Spinners。 我想知道的是如何讓ListView或Spinner選擇的項目與相應的行具有相同的ID?來自數據庫的Android SimpleCursorAdapter ID

奇怪的是,這部作品與文本菜單,這是我現在用直記事本實例:

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
info.id 

此ID字段IS一樣rowid的桌子上,我可以刪除項目的罰款,但當我嘗試這樣的事情:

getListView().setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> adapter, View view, 
       int position, long arg) { 
      Intent i = new Intent(getApplicationContext(), 
        FuelingList.class); 
      long id = view.getId(); 

該ID字段是一些隨機不明確。 所以我的問題是,在第一個代碼位中,什麼是AdapterContextMenuInfo獲取以及如何在代碼的其他部分檢索它?

+0

對不起,我不知道。會做,謝謝! – vascoFG

+0

另外,如果我需要訪問所選項目的ID,那麼在代碼的任何其他位置(不是監聽器),是否有比使用'((SimpleCursorAdapter)item.getAdapter())更簡單的方法 \t \t \t \t \t \t \t \t \t .getCursor()。getLong( \t \t \t \t \t \t \t \t \t \t \t((SimpleCursorAdapter)fuelType \t \t \t \t \t \t \t \t \t \t \t \t \t .getAdapter())。getCursor() \t \t \t \t \t \t \t \t \t \t \t \t \t .getColumnIndex( 「_ ID」))'? – vascoFG

回答

3

由於您使用的是SimpleCursorAdapter,該onItemClick正在通過數據庫行ID在給你..

 public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) 

long arg部分實際上是您的數據庫行ID。

所以,你的代碼應該是:

getListView().setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> adapter, View view, 
      int position, long arg) { 
     Intent i = new Intent(getApplicationContext(), 
       FuelingList.class); 
     long id = arg; 
3

既然你知道你用的是SimpleCursorAdapter,然後在onItemClick方法,你可以調用

public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) { 
    String value = ((SimpleCursorAdapter) adapter.getAdapter()).getCursor().getString(COLUMN_INDEX); 
} 

COLUMN_INDEX在您想要從當前選擇行中的遊標來獲取該列。

或者,調用

adapter.getAdapter().getItem(position) 

,然後流延到Cursor,工作也是如此。

注1:AdapterView實際上是你ListView

注2:由於你在適配器使用SimpleCursorAdapter然後getItem(position)返回位於行您specifed

注3 Cursor:當你有Cursor,可以獲取通過提供列索引數據(0基於)或使用cursor.getString(cursor.getColumnIndex("COLUMN_NAME"))

注4:使用按巴拉克的評論的arg參數是從_ID字段中的值時,CursorAdapter,如果你需要知道的是該行_ID,然後只需使用arg值。

+0

我得到這個錯誤'不能從AdapterView 轉換爲SimpleCursorAdapter'。 還有我不是拯救ID上的ListView的任何領域,但菜單似乎能夠訪問它... – vascoFG

+0

也許嘗試,((SimpleCursorAdapter)getListView()。getAdapter())。getCursor()代替。 – stuckless

+0

它無效,我得到無效的轉換錯誤。 這裏真正的問題是,AdapterContextMenuInfo如何獲得正確的ID? – vascoFG

0

您可以將行的id存儲在arraylist中,並從arraylist的相應位置獲取行的id。這個工作對我..

protected void onListItemClick(ListView l, View v, int position, long id) { 
    // TODO Auto-generated method stub 
    super.onListItemClick(l, v, position, id); 

    Intent intent=new Intent(this , Details.class); 
    Bundle extras = new Bundle(); 
    extras.putLong("ID", IDList.get(position)); 
    intent.putExtras(extras); 
    startActivityForResult(intent, SHOW_DETAILS); 

} 

您可以使用listview.setonitenclicklistener ...希望它可以幫助

相關問題