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

Android开发:SQLite查询遇CursorIndexOutOfBoundsException错误求助

解决Android SQLite CursorIndexOutOfBoundsException问题

你遇到的CursorIndexOutOfBoundsException是因为当stories表中没有任何数据时,你的代码仍然强行尝试从游标里读取内容。具体来说,cursor.moveToFirst()在表为空时会返回false,但你用的do-while循环会先执行一次循环体——这时候游标还停留在初始的无效位置(索引-1),调用cursor.getString()自然就会触发越界异常。

我帮你修正一下getTitleAndImage()方法的逻辑,同时做一些小优化:

public ArrayList<StoryModel> getTitleAndImage(){
    ArrayList<StoryModel> myData = new ArrayList <> ();
    SQLiteDatabase db= this.getReadableDatabase();
    // 只查询需要的两列,比查所有列更高效
    Cursor cursor =db.rawQuery("SELECT story_title, story_image FROM stories ",null);
    
    // 先判断游标是否有效且存在数据
    if (cursor != null && cursor.moveToFirst()) {
        // 用while循环替代do-while,确保有数据才执行循环体
        while (!cursor.isAfterLast()) {
            StoryModel forDoing=new StoryModel();
            // 提前获取列索引,避免每次循环重复查找,提升性能
            int titleColumnIndex = cursor.getColumnIndex("story_title");
            int imageColumnIndex = cursor.getColumnIndex("story_image");
            
            // 增加列索引有效性判断,防止列名写错导致异常
            if (titleColumnIndex != -1) {
                forDoing.setTitle(cursor.getString(titleColumnIndex));
            }
            if (imageColumnIndex != -1) {
                forDoing.setImage(cursor.getString(imageColumnIndex));
            }
            
            myData.add(forDoing);
            cursor.moveToNext();
        }
        cursor.close();
    }
    db.close();
    return myData;
}

另外,在MainActivity里也可以加个判断,避免遍历空列表:

ArrayList<StoryModel> TitleAndImage = mySQL.getTitleAndImage();
if (!TitleAndImage.isEmpty()) {
    for (StoryModel storyModel : TitleAndImage) {
        Log.d("story_title", storyModel.getTitle());
        Log.d("story_image", storyModel.getImage());
    }
} else {
    Log.d("db_info", "数据库里还没有任何故事数据哦");
}

这些修改主要做了这几件事:

  • 只查询需要的列,减少不必要的数据读取
  • 增加游标非空和数据存在的判断,避免无效操作
  • 用while循环替代do-while,确保只有有数据时才执行读取逻辑
  • 提前获取列索引并增加有效性判断,提升性能同时避免列名错误导致的异常

内容的提问来源于stack exchange,提问作者Abdullah Khudher

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:34:24