我有一类具有两列 CATEGORY_ID
和名称
。我创建了一个名为数据助手类 CategoryDataHelper
。我有一个名为方法 getCategoryCursor()
其获取从类别表中的ID和名称,并返回游标,辅助类的。使用游标,我已经使用 SimpleCursorAdapter
来显示类别列表。这是工作的罚款。
公共类分类扩展ListActivity {
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
categoryDataHelper =新CategoryDataHelper(getApplicationContext());
光标categoryCursor = categoryDataHelper.getCategoryCursor();
ListAdapter适配器=新SimpleCursorAdapter(
本,
android.R.layout.simple_list_item_1,
categoryCursor,
新的String [] {} CategoryDataHelper.NAME,
新的INT [] {android.R.id.text1});
//绑定到我们新的适配器。
setListAdapter(适配器);
表= getListView();
list.setOnItemClickListener(新OnItemClickListener(){
@覆盖
公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长的id){
//这里我想CATEGORY_ID
}
});
}
}
现在我想实现一个 OnItemClickListener
并发送所选类别的意图与 CATEGORY_ID
。我怎样才能在 onItemClick()
法的ID?
您也许应该从适配器光标。这样,如果你的光标被替换你仍然仍然得到一个有效的光标。
光标光标=((SimpleCursorAdapter)适配器视图).getCursor();
cursor.moveToPosition(位置);
长的categoryId = cursor.getLong(cursor.getColumnIndex(CategoryDataHelper.ID));
或使用CATEGORY_ID
或任何你列的名称很到位 CategoryDataHelper.ID
。
I have a category table with two columns category_id
and name
. I have created a data helper class named CategoryDataHelper
. I have a method named getCategoryCursor()
of that helper class which fetches the id and the name from the category table and returns the cursor. Using that cursor, I have used SimpleCursorAdapter
to display the list of categories. It is working fine.
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
}
});
}
}
Now I want to implement an OnItemClickListener
and send an Intent with the category_id
of the selected category. How can I get the id in the onItemClick()
method?
You probably should get the cursor from the adapter. This way if your cursor gets replaced you are still are still getting a valid cursor.
Cursor cursor = ((SimpleCursorAdapter) adapterView).getCursor();
cursor.moveToPosition(position);
long categoryId = cursor.getLong(cursor.getColumnIndex(CategoryDataHelper.ID));
or use "category_id"
or whatever the name of your column is in place of CategoryDataHelper.ID
.