Search code examples
androidlistviewcursoradapterlistadapter

getItem(position) returns same object for different values of position


I have a adapter with the following piece of (test) code in public View getView(int position, View convertView, ViewGroup parent):

    Cursor itemCursor = (Cursor) getItem(position);
    Cursor itemCursor2 = (Cursor) getItem(position+1);

    String itemTitle = itemCursor.getString(itemCursor
            .getColumnIndex(ItemColumns.TITLE));
    String itemTitle2 = itemCursor2.getString(itemCursor2
            .getColumnIndex(ItemColumns.TITLE));

I override "DragSortCursorAdapter" so getItem() is overridden to look like this:

@Override
public Object getItem(int position) {
    int item = mListMapping.get(position, position);
    return super.getItem(item);
    //return super.getItem(position);
}

the getItem which is called from here is the normal implementation from "android.support.v4.widget.CursorAdapter.getItem"

The problem is that itemCursor and itemCursor2 always is the same object. With same object ID and everything - I have no idea how this is possible since getItem is called with different arguments, and the list I output to the screen only shows different values.

In other words, when my adapter iterates the list it seems to do like this:

First list Item:

Cursor itemCursor = (Cursor) getItem(0);
Cursor itemCursor2 = (Cursor) getItem(0+1);

itemCursor and itemCursor2 are both 413d4800

Second list Item:

Cursor itemCursor = (Cursor) getItem(1);
Cursor itemCursor2 = (Cursor) getItem(1+1);

itemCursor and itemCursor2 are now both 4155aef8

Shouldn't at least itemCursor2 from the first iteration and itemCursor2 from the second iteration be identical?

In any case - can someone please help me with what is going on here? They both have the type "android.content.ContentResolver$CursorWrapperInner@4155aef8" which may or may not be relevant - I'm not sure.

EDIT The overridden getItem() is working. mListMapping.get(position, position); returns the correct value and item is indeed two different numbers - returning the same object.


Solution

  • The problem is that itemCursor and itemCursor2 always is the same object.

    Correct.

    I have no idea how this is possible since getItem is called with different arguments

    Lots of methods can return the same value given different arguments.

    A CursorAdapter wraps a Cursor. getItem() will always return this Cursor. However, getItem() will position the internal index of the Cursor to be the specified position. Hence, while the Cursor itself is the same object, what the Cursor returns for methods like getString() will differ, because the internal position within the Cursor is different.

    You can see this in action by examining getItem() in the CursorAdapter source code.