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

Android CursorIndexOutOfBoundsException报错求助:游标索引越界

问题分析与解决

核心错误原因

  • 变量名误用:报错行写的是cursor.getString(17),但你实际定义的游标对象是cursor_other_card,这里误用了未初始化的cursor变量,直接导致游标索引越界。
  • 硬编码索引隐患:就算修正变量名,硬编码列索引(比如17、18)的写法也很脆弱——一旦SELECT语句调整列顺序,就会出现索引对应列不匹配的问题。
  • SQL注入风险:直接把id拼接到SQL语句里,不仅可能导致查询结果异常,还存在SQL注入安全问题。

修复步骤

1. 修正游标变量名

把报错行的cursor全部替换为cursor_other_card:

myEdit.putString("others_reason_not_presented"+i+"_u", cursor_other_card.getString(17));
myEdit.putString("others_reason_unclaimed"+i+"_u", cursor_other_card.getString(18));

2. 用列名替代硬编码索引

通过列名获取索引,避免列顺序变动引发的错误:

// 先获取列索引
int othersNotPresentedIdx = cursor_other_card.getColumnIndex("others_reason_not_presented");
int othersUnclaimedIdx = cursor_other_card.getColumnIndex("others_reason_unclaimed");

// 检查索引有效后再取值
if (othersNotPresentedIdx != -1) {
    String value = cursor_other_card.isNull(othersNotPresentedIdx) ? "" : cursor_other_card.getString(othersNotPresentedIdx);
    myEdit.putString("others_reason_not_presented"+i+"_u", value);
}
if (othersUnclaimedIdx != -1) {
    String value = cursor_other_card.isNull(othersUnclaimedIdx) ? "" : cursor_other_card.getString(othersUnclaimedIdx);
    myEdit.putString("others_reason_unclaimed"+i+"_u", value);
}

3. 修复SQL注入问题

改用参数化查询代替字符串拼接:

String sql = "SELECT ocv.id,ocv.card_holder_name,ocv.card_number_system_generated,ocv.card_number_inputted,ocv.card_number_series,ocv.distribution_status,ocv.release_date,ocv.release_by,ocv.release_place,ocv.card_physically_presented,ocv.card_pin_is_attached,ocv.reason_not_presented,ocv.reason_unclaimed,ocv.card_replacement_requests,ocv.card_replacement_request_submitted_details,ocv.pawning_remarks,ocv.other_image, ocv.others_reason_not_presented,ocv.others_reason_unclaimed FROM other_card_validations AS ocv LEFT JOIN emv_validation_details AS evd ON evd.id = ocv.emv_validation_detail_id WHERE evd.id=?";
Cursor cursor_other_card = MainActivity.sqLiteHelper.getReadableDatabase().rawQuery(sql, new String[]{String.valueOf(id)});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:45:31