Android - Getting database ID from ListView selection

后端 未结 2 1980
温柔的废话
温柔的废话 2021-01-28 17:07

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

相关标签:
2条回答
  • 2021-01-28 17:37

    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
        }
    });
    
    0 讨论(0)
  • 2021-01-28 17:50

    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.

    0 讨论(0)
提交回复
热议问题