Android Cursor find row with specific value

176 Views Asked by At

I have a ListView with a SimpleCursorAdapter. Loaded from a DB table; 400 rows.

I want to scroll the row into view with column "name='xxx'". The cursor is sorted by name.

I know about the ListView 'Scroll' methods. But they require a position.

What is the proper efficient way to scroll that row into view?

I don't know of anyway to find that row in the Cursor without iterating over every row (yes, I can do a binary search) to find the row with matching name=xxx in order to get the position required by the ListView 'Scroll' methods.

Here is my current code that does a binary search for the name to scroll to. It seems inefficient or like there ought to be another built-in method. Just seems as though there ought to be a 'cursor.find(colName, value)' method that returns a position.

public void scrollToName(String name) {
    // Scroll to Name using Binary Search for name
    int compareResult;
    int startIndex = 0;
    int lastIndex = checklistCursor.getCount() - 1;
    int curIndex = ((lastIndex - startIndex) / 2) + startIndex;
    // Position cursor
    checklistCursor.moveToPosition(curIndex);
    // Get name at cursor
    String curName = checklistCursor.getString(checklistCursor.getColumnIndex(nameField));
    // Find row that contains name
    while ((compareResult = name.compareToIgnoreCase(curName)) != 0) {
        if (compareResult > 0) {
            startIndex = curIndex + 1;
        } else {
            lastIndex = curIndex - 1;
        }
        curIndex = ((lastIndex - startIndex) / 2) + startIndex;
        checklistCursor.moveToPosition(curIndex);
        curName = checklistCursor.getString(checklistCursor.getColumnIndex(nameField));
    }
    // Exit While Loop with position set to searched name
    // Scroll to that position.
    checklistView.smoothScrollToPositionFromTop(curIndex, (checklistView.getHeight() / 2),
            200);
}
0

There are 0 best solutions below