Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position of an item within a ListView?

Tags:

java

android

How would one find the position of a specific item within a ListView? (Populated by SimpleCursorAdapter).

The reason I ask: The listview is set to singleChoice mode. When the user closes and reopens the app, I'd like the user's selection to be remembered.

The way I've done it so far is when the user clicks on an item, the ID of the chosen item is saved to preferences. What I need to learn is how to reselect the item in the activity's onCreate method once it's been repopulated.

My code for saving the selected item's ID:

    @Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    Cursor c = (Cursor) l.getItemAtPosition(position);
    selectedItem = c.getLong(c.getColumnIndex("_id"));
}

(I've tried googling, but only seem to find how to get the position of the selected item)

Thanks!

like image 491
CL22 Avatar asked Apr 16 '11 06:04

CL22


2 Answers

You should try

//SimpleCursorAdapter adapter;
final int position = adapter.getCursor().getPosition();

API Docs:

public abstract int getPosition () 

Since: API Level 1

Returns the current position of the cursor in the row set. The value is zero-based. When the row set is first returned the cursor will be at positon -1, which is before the first row. After the last row is returned another call to next() will leave the cursor past the last entry, at a position of count().

Returns the current cursor position.

Update

To get an item's position based on the id used by the adapter:

private int getItemPositionByAdapterId(final long id)
{
    for (int i = 0; i < adapter.getCount(); i++)
    {
        if (adapter.getItemId(i) == id)
            return i;
    }
    return -1;
}

To get an item's position based on the underlying object's properties (member values)

//here i use `id`, which i assume is a member of a `MyObject` class, 
//and this class is used to represent the data of the items inside your list:
private int getItemPositionByObjectId(final long id)
{
    for (int i = 0; i < adapter.getCount(); i++)
    {
        if (((MyObject)adapter.getItem(i)).getId() == id)
            return i;
    }
    return -1;
}
like image 86
rekaszeru Avatar answered Sep 28 '22 07:09

rekaszeru


I do this straightforward in my own app:

long lastItem = prefs.getLong(getPreferenceName(), -1);
if (lastItem >= 0) {
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        if (lastItem == cursor.getLong(0)) {
            spinner.setSelection(cursor.getPosition());
            break;
        }
        cursor.moveToNext();
    }
}

Spinner is populated with the cursor's contents, so I just look through them and compare with the selected item id. In your case that would be a ListView.

like image 37
Malcolm Avatar answered Sep 28 '22 06:09

Malcolm