Get selected item from ListView bound with SimpleCursorAdapter

风流意气都作罢 提交于 2019-11-27 10:52:19
Femi

So a couple of points: after you fetch the cursor, you want to call startManagingCursor. This ties the cursor's lifecycle with Activity's lifecycle (so when the Activity gets destroyed the cursor gets closed/cleaned up).

startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(
        this, 
        android.R.layout.simple_list_item_1,  
        c,        
        new String[] {"name"},   
        new int[] {android.R.id.text1}); 
setListAdapter(adapter);

Also, the database isn't closed, the Cursor typically keeps a live connection to the DB (so the ListView can scroll and do things of that nature that may require future access to the Cursor's contents.

To your core question, the easiest way to do it in onListItemClick is this:

Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);

You can then use the c.getLong(0) to get the id (assuming you fetched the id column as the first column which is generally the case). However, note that the id is passed in as part of the signature (see the last argument in public void onListItemClick(ListView l, View v, int position, long id)) so you really don't need to fetch it again (but you certainly can if you want to burn the cycles). For accessing other columns you can do the same thing, just change the column index.

Hope that helps.

Another way:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {

            Cursor cursor = (Cursor) parent.getAdapter().getItem(position);
            //TODO
            }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!