android.database.CursorIndexOutOfBoundsException

后端 未结 3 1278
再見小時候
再見小時候 2021-02-14 15:21

The data access code in my Android app raises an exception.

Here is the code that causes the exception:

String getPost = \"SELECT * FROM \" + TABLE_POST          


        
3条回答
  •  广开言路
    2021-02-14 15:49

    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("")

提交回复
热议问题