Search code examples
androidsqlitecursor

Cursor Index Issue


Can anyone please explain why this method in my database helper class is not working properly. I query a table named Tutorial with a layout column.

public String getLayout(int layout_position)
{
    String SQL = "SELECT * FROM Tutorial";
    Cursor cursor = database.rawQuery(SQL, null);

    cursor.moveToFirst();
    cursor.move(layout_position);
    String layout = cursor.getString(cursor.getColumnIndex("layout"));
    System.out.println(">>>DBhelper->getLayout: "+ layout);

    return (layout);
}

The cursor is moved by int layout_position, which is incremented every time before I call the method. Everything actually works just fine until layout_position reaches 2. Then I get this error from logcat

07-20 09:35:41.479: E/AndroidRuntime(4630): android.database.CursorIndexOutOfBoundsException: Index 2 requested, with a size of 2

The Tutorial table is pre-populated with 4 rows, so I'm not sure what is happening here?


Solution

  • cursor.move moves the cursors position by the amount specified in the argument. You are most likely looking for cursor.moveToPosition(layout_position)