Android SQLite游标越界异常(CursorIndexOutOfBoundsException)求助
解决SQLite游标越界(CursorIndexOutOfBoundsException)问题
你碰到的这个CursorIndexOutOfBoundsException问题,根源出在循环条件的判断逻辑上!
看你的代码,循环用了while (c != null)——但游标对象本身永远不会变成null,哪怕已经遍历完所有561条记录,c还是那个游标实例,只是它的位置已经跳到了最后一条记录的后面(索引561,而你的记录索引范围是0到560),这时候再去调用c.getString(),自然就触发了越界异常。
正确的遍历方式
这里给你两种常用的、不会出错的游标遍历写法:
写法一:用moveToNext()作为循环条件
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM product", null); if (c != null) { int barcodeIndex = c.getColumnIndex("barcode"); int descriptionIndex = c.getColumnIndex("description"); int brandIndex = c.getColumnIndex("brand"); // 直接用moveToNext()判断是否还有下一条记录 while (c.moveToNext()) { String textString = "Product - [" + c.getString(barcodeIndex) + "][" + c.getString(descriptionIndex) + "][" + c.getString(brandIndex) + "]"; Log.i("SQL-Log", textString ); } c.close(); }
写法二:do-while循环(适合先确认有数据的场景)
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM product", null); if (c != null && c.moveToFirst()) { int barcodeIndex = c.getColumnIndex("barcode"); int descriptionIndex = c.getColumnIndex("description"); int brandIndex = c.getColumnIndex("brand"); // 先执行一次循环体,再判断是否有下一条 do { String textString = "Product - [" + c.getString(barcodeIndex) + "][" + c.getString(descriptionIndex) + "][" + c.getString(brandIndex) + "]"; Log.i("SQL-Log", textString ); } while (c.moveToNext()); c.close(); }
额外的最佳实践提醒
- 一定要检查游标是否为
null,避免空指针异常; - 调用
getColumnIndex()后,可以判断返回值是否为-1(如果列名拼写错误,会返回-1),提前处理异常情况; - 推荐用
try-finally包裹游标操作,确保游标一定会被关闭,防止数据库资源泄漏:
Cursor c = null; try { c = sqLiteDatabase.rawQuery("SELECT * FROM product", null); if (c != null && c.moveToFirst()) { int barcodeIndex = c.getColumnIndex("barcode"); // ... 遍历逻辑 } } finally { if (c != null) { c.close(); } }
内容的提问来源于stack exchange,提问作者Adam Buckland
相关产品推荐
相关产品推荐

