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

Android项目SQLite Cursor仅返回首条数据,如何获取第二条?

哦,这个问题我之前也碰到过!你的代码现在只取了第一条数据,而且还有数组越界的隐患,我来给你拆解下问题和解决办法:

首先说下你现有代码的问题:

  • 你初始化的String[] subjects = {}是个空数组,长度为0,直接给subjects[0]赋值肯定会触发ArrayIndexOutOfBoundsException,你没提到这个可能是还没运行到这一步?
  • 只调用了c.moveToFirst()然后取了第一条数据,没有遍历Cursor里的所有记录,自然拿不到第二条Chemistry。

接下来给你两种靠谱的解决方式,推荐第一种:

方式一:用ArrayList动态存储(推荐)

因为你没法提前知道数据库里有多少条数据,用ArrayList可以灵活添加元素,之后再转成数组:

// 先创建一个动态列表
List<String> subjectList = new ArrayList<>();
Cursor c = db.rawQuery("SELECT * FROM subs", null);

// 先判断Cursor不为空,避免空指针
if (c != null) {
    // 用while循环遍历所有记录,moveToNext会自动走到下一条,直到没有数据
    while (c.moveToNext()) {
        // 这里强烈建议用列名获取索引,而不是直接写0!
        // 万一之后表结构调整,列顺序变了,直接用索引会取错数据
        int subNameIndex = c.getColumnIndex("subname");
        String subName = c.getString(subNameIndex);
        subjectList.add(subName);
    }
    // 一定要关闭Cursor,不然会内存泄漏
    c.close();
}

// 把列表转成String数组
String[] subjects = subjectList.toArray(new String[0]);

方式二:先获取计数再初始化数组

如果你一定要用数组,可以先获取Cursor的总记录数,再创建对应长度的数组:

String[] subjects = new String[0];
Cursor c = db.rawQuery("SELECT * FROM subs", null);

if (c != null) {
    int totalCount = c.getCount();
    subjects = new String[totalCount];
    int currentIndex = 0;

    // 先移动到第一条,然后用do-while循环遍历
    if (c.moveToFirst()) {
        do {
            String subName = c.getString(c.getColumnIndex("subname"));
            subjects[currentIndex++] = subName;
        } while (c.moveToNext());
    }
    c.close();
}

另外再给你个小建议:如果你的项目用的是Java 7及以上,最好用try-with-resources语法,这样Cursor会自动关闭,不用手动写close,更安全:

try (Cursor c = db.rawQuery("SELECT * FROM subs", null)) {
    List<String> subjectList = new ArrayList<>();
    while (c.moveToNext()) {
        String subName = c.getString(c.getColumnIndex("subname"));
        subjectList.add(subName);
    }
    String[] subjects = subjectList.toArray(new String[0]);
    // 在这里使用你的subjects数组就好
} catch (Exception e) {
    e.printStackTrace();
}

这样改完之后,就能拿到包含Physics和Chemistry的数组啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:20:57