Android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 10
android 中數(shù)據(jù)庫處理,特別是使用cursor時,注意初始位置,好像是從下標為-1的地方開始的,也就是說一次查詢中,返回給cursor查詢結(jié)果時,不能夠馬上從cursor中提取值。
比如,下面的代碼會返回錯誤,android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 0:
int score = ((Cursor)getReadableDatabase().query(TABLE_NAME, new String[]{"learned"}, "_id=?", new String[]{""+id}, null, null, null,"1")).getInt(0);
正確的用法:
Cursor cursor = getReadableDatabase().query(TABLE_NAME, new String[]{"learned"}, "_id=?", new String[]{""+id}, null, null, null,"1");
int learned=0;
if(cursor.moveToFirst()){
score= cursor.getInt(0);
}
cursor.close();
|