android.database.CursorIndexOutOfBoundsException

浪子不回头ぞ 提交于 2019-12-03 13:05:28
Simon Dorociak

You are attempting to retrieve an item on index 2 but this index really doesn't exist (Cursor size is 2 so indexes are 0,1).

Change your loop:

if (result != null && result.moveToFirst()){
    do {
       Post post = new Post();
       post.setPostId(result.getInt(0));
       posts.add(post);
       ....
    } while (result.moveToNext());
}

Now it should work correctly.

Note: Don't forget to call moveToFirst() method that moves Cursor into the first record (implicitly is positioned before the first row) and prepares it for reading. This is also a handy method for testing whether Cursor is valid or not.

Note 2: Don't use column indexes, you can simply make a mistake in counting. Instead of use column names - this approach is generally recommended e.q. cursor.getColumnIndex("<columnName>")

You havent moved cursor index to first .. Try like this below

 String getPost = "SELECT * FROM " + TABLE_POST + ";";
    Cursor result = getReadableDatabase().rawQuery(getPost, null);
    List posts = new ArrayList();{
    Log.d("count", result.getCount() + " post rows");

    if (result .moveToFirst()) {
        do {
             Post post = new Post();
             post.setPostId(result.getInt(0));
             posts.add(post);
              ....
        } while (result .moveToNext());
    }
    result .close();

This arises in the case our Cursor has data but not yet pointing to first index in the data list.

To get avoid this exception, we first should check:

if (!cursor.moveToFirst())
        cursor.moveToFirst();

And then carry the further actions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!