Cursor index out of bounds

2019-08-17 13:43发布

I am encountering cursor index out of bounds exception.

My code is as follows.

SQLiteDatabase db = this.getWritableDatabase();
String completedInList = "SELECT COUNT(*) FROM " + TABLE_BUCKET_ITEMS + " WHERE "
                + KEY_BUCKET + " = " + bucketNo + " AND " + KEY_FLAG + " = 1" ;

Cursor cursor = db.rawQuery(completedInList, null);
int completed = Integer.parseInt(cursor.getString(0));

String totalNoList = "SELECT COUNT(*) FROM " + TABLE_BUCKET_ITEMS + " WHERE "
                + KEY_BUCKET + " = " + bucketNo;
cursor.close();

Cursor cursor2 = db.rawQuery(totalNoList, null);
int total = Integer.parseInt(cursor2.getString(0));

float percentage = ((float)completed) / total;

cursor2.close();
db.close();

I expect that the return value of the sql query is a number that's why I code the index to 0 as follows: cursor.getString(0)

But why am I encountering an cursor index out of bounds?

1条回答
SAY GOODBYE
2楼-- · 2019-08-17 14:04

Doc says rawQuery returns

A Cursor object, which is positioned before the first entry

So you seem to need call moveToFirst before using cursor.getString

查看更多
登录 后发表回答