Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override the getItemId(int pos) method from CursorAdapter?

I am getting this question due to another answer on here, but didn't explain how to do what I am asking How to get the id of the row in onItemClick(ListView) when using a custom Adapter?

The answer which was accepted in that question is what I need since I am also making my own custom adapter (CursorAdapter), hence I will have the same problem. The problem is I have no idea how to accomplish that. I am looking at the Doc, and am not sure how to access the _id column from a cursor. Since the Doc doesn't have the constant which we can get that info from I'm stuck. Any help figuring it out would be much appreciated.

EDIT: I was not clear on what my question was, but just to clarify, like the title, how can I override the getItemId() method in the CursorAdapter custom class I created?

like image 376
Andy Avatar asked Jun 05 '12 03:06

Andy


2 Answers

Assuming you don't have the Cursor as a member of your Adapter:

@Override
public long getItemId(int position) {
    Cursor cursor = getCursor();
    cursor.moveToPosition(position);
    return cursor.getLong(mCursor.getColumnIndex("_id"));
}
like image 163
Sam Avatar answered Nov 11 '22 00:11

Sam


I nkow this doesn't answer the question posed, but Sam took care of that. I thought I'd post this because there seems to be some confusion on the OPs part.

Following is an onListItemClick method from an activity that contains a list created with a custom cursor adapter:

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Your code here
}

long id is the row id for the data contained in the row clicked (when the list is fed by a cursor adapter). No need to override getItemId.

You only need to override the getItemId (in my experience) if you do something like put information from different rows into a single line. As long as all your data for a list line is from the same row in the database, there's no need to go to that trouble.

I suppose another time you may need to use it would be if you took data from a cursor and put it into an array and then used an array adapter.. but that seems pretty roundabout...

like image 44
Barak Avatar answered Nov 11 '22 00:11

Barak