You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:41:28