android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1

来源:互联网 发布:sqlserver 设置主键 编辑:程序博客网 时间:2024/05/16 07:25

android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1

android 中数据库处理,特别是使用cursor时,注意初始位置,好像是从下标为-1的地方开始的,也就是说一次查询中,返回给cursor查询结果时,不能够马上从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();