user817129
user817129

Reputation: 522

Cursor Index Out of Bounds Exception

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

Upvotes: 2

Views: 14036

Answers (2)

ijavid
ijavid

Reputation: 715

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

Upvotes: 2

pawelzieba
pawelzieba

Reputation: 16082

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.

Upvotes: 13

Related Questions