Cursor Index Out of Bounds Exception

你离开我真会死。 提交于 2019-12-19 04:12:57

问题


In attempting to execute a query on my database, I get this exception. However, the documentation states that the method SQLiteDatabase.query(...) returns, "A Cursor object, which is positioned before the first entry," which I interpret to mean that the Cursor is at the start of the rows returned. If I add the Cursor.moveToFirst() before accessing data in the Cursor, I get no exception. What is going on? Do I need to always call "moveToFirst" before trying to get data? The documentation says this method, "moves the cursor to the first row."

Cursor c = db.query(TABLENAME, null, null, null, null, null, null);
Log.d("TAG",""+c.getInt(c.getColumnIndex("_id")));

回答1:


After query you need to call next() or moveToFirst(). Cursors are lazy loaded, after calling these methods cursor is loaded into memory. You can decide when to do it.




回答2:


to iterate trough all rows:

Cursor c = db.query(TABLENAME, null, null, null, null, null, null); 
while(c.moveToNext()) {
      int id = c.getInt(c.getColumnIndex("_ID")); 
}

or you can use other cursor functions, for example moveToPosition() to access row specified by id

more info: http://developer.android.com/reference/android/database/Cursor.html



来源:https://stackoverflow.com/questions/6743833/cursor-index-out-of-bounds-exception

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