CursorIndexOutOfBoundsException:请求索引2,大小为2.如何解决? &g



查询SQLite数据库时,只显示2行。有可能修复这个错误吗?

Cursor cursor = database.rawQuery("SELECT * FROM Category", null);
cursor.moveToFirst();
for (int i = 0; i < 10; i++) {
categoryList.add(new Category(cursor.getInt(0), cursor.getString(1)));
cursor.moveToNext();
}
cursor.close();
database.close();

错误:

Process: com.triangle.learningenglish, PID: 30477
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.triangle.learningenglish/com.triangle.learningenglish.Select.SelectCategory}: android.database.CursorIndexOutOfBoundsException: Index 2 requested, with a size of 2

该错误的原因是您没有检查游标是否为空。您只需在for循环中循环并检索可能有值或没有值的结果。
我想这行代码解决了你的问题

Cursor cursor = database.rawQuery("SELECT * FROM Category", null);

int numberOfRows = cursor.getCount();
int counter = 1;
cursor.moveToFirst();
while(numberOfRows !=0 && counter <= numberOfRows){
categoryList.add(new Category(cursor.getInt(0), cursor.getString(1)));
counter++;
cursor.moveToNext();
}
cursor.close();
database.close();

最新更新