Android - Getting database ID from ListView select

2019-03-03 08:18发布

I have a ListView lv which uses a Cursor c from an SQL database to populate it. When an item is selected however, I need to get the ID of the row. How can I do this?

2条回答
手持菜刀,她持情操
2楼-- · 2019-03-03 08:21

I assume that you are using a SimpleCursorAdapter (or similar), so I would use the OnItemClickListener:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // id references the SQLiteDatabase _id column
    }
});
查看更多
祖国的老花朵
3楼-- · 2019-03-03 08:29

Here's how it worked out for me. In an other class, I have created a method of List type and added the column id & the name of the item in the list from the sqlite database.

Here's the piece of code to retrieve the column id of the selected item.

    public List<String> list;
    adapt = new MyAdapter(this, R.layout.list_inner_view, list); //custom adapter
    listTask.setAdapter(adapt);

    listTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {

           Integer id = list.get(position).getId();
          //position is the position of the item in the list.
       }
   });

Result: the item is at 3rd position in the list. Its database column_id (auto increment) value is 12 because I have deleted previous items. So the result you expect is 12, which is the value of variable id.

If you don't understand this fully, it may be because I haven't posted my entire code. But I'll help you out with your problem.

查看更多
登录 后发表回答