2011-04-05 68 views
5

我有一个包含两列category_idname的类别表。我创建了一个名为CategoryDataHelper的数据帮助类。我有一个名为getCategoryCursor()的方法,它从类别表中提取id和名字并返回游标。使用该光标,我使用SimpleCursorAdapter来显示类别列表。它工作正常。如何在onItemClick处理程序中获取物品ID

public class Categories extends ListActivity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     categoryDataHelper = new CategoryDataHelper(getApplicationContext()); 
     Cursor categoryCursor = categoryDataHelper.getCategoryCursor(); 
     ListAdapter adapter = new SimpleCursorAdapter (
       this, 
       android.R.layout.simple_list_item_1, 
       categoryCursor,            
       new String[] { CategoryDataHelper.NAME },   
       new int[] {android.R.id.text1}); 

     // Bind to our new adapter. 
     setListAdapter(adapter); 

     list = getListView(); 
     list.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       // Here I want the category_id 
      } 
     }); 
    }  
} 

现在我想实现一个OnItemClickListener与所选类别的category_id发送意图。我如何获得onItemClick()方法中的ID?

+0

是不是ID参数类型长帮助你? – 2011-04-05 14:09:45

+0

要获取所选项目的内容,请使用 Object o = lv.getItemAtPosition(position); 对象o可以进一步用于获取项目。 – 2011-04-05 14:11:06

+0

setListAdapter是做什么的,它为什么会出现在list = getListView()之前? – 2011-04-05 14:13:51

回答

17

您可能应该从适配器获取光标。这样,如果你的光标被替换,你仍然得到一个有效的光标。

Cursor cursor = ((SimpleCursorAdapter) adapterView).getCursor(); 
cursor.moveToPosition(position); 
long categoryId = cursor.getLong(cursor.getColumnIndex(CategoryDataHelper.ID)); 

或使用"category_id"或任何你列的名称是到位的CategoryDataHelper.ID

+9

'adapterView'通常不是一个适配器。这是一个使用适配器的视图,因此具有getAdapter()方法。所以,在你的例子中,你应该调用'adapterView.getAdapter()'来代替。 – 2013-01-30 15:00:58

+0

它适用于'SimpleAdapter'吗? – Apurva 2015-02-08 16:52:49

1

如何在onItemclick:

categoryCursor.moveToPosition(position); 

,然后从返回的光标从你的帮手ID?

+0

怎么可能...你可以给代码示例 – 2011-04-05 14:19:29

2

谢谢扎克,我可以解决您的帖子...超棒! ... 我送参数从活动到另一个这样:

Intent myIntent = new Intent(Clientes.this, Edc.class); 
Cursor cursor = (Cursor) adapter.getItem(position); 
myIntent.putExtra("CLIENTE_ID", cursor.getInt(cursor.getColumnIndex("_id"))); 
startActivity(myIntent); 

在其他活动(EDC)......我得到的参数,以便:

int _clienteId = getIntent().getIntExtra("CLIENTE_ID", 0); 
1

随着SimpleCursorAdapteronItemClick函数传递所选项目的数据库ID。所以,解决办法很简单:

long category_id = id 
相关问题