查询sqlite数据库有outofboundException

query sqlite database has outofboundException

我有一个 ArrayList,我尝试将其转换为 String[],这样我就可以查询我的数据库,但我得到了 outofboundException,我不知道问题出在哪里?

将数组列表转换为字符串[] :

String[] idsArray = new String[selectedTopicIds.size()];
    idsArray = selectedTopicIds.toArray(idsArray);
    for (int i = 0; i < selectedTopicIds.size(); i++) {
        idsArray[i] = selectedTopicIds.get(i);
    }

那我用游标查询:

Cursor cursor = myDb.query(Util.TABLE_NAME,
            null,
            Util.KEY_TOPIC + "=?",
            idsArray,
            null,
            null,
            null);

这就是游标循环的方式:

if (cursor.moveToFirst()) {
        do {
            Word word = new Word();
            word.setId(cursor.getInt(0));
          
            wordList.add(word);

        } while (cursor.moveToNext());
    }
    cursor.close();

在我给它的那一行 idsArray 我有这个例外:

java.lang.IllegalArgumentException: Cannot bind argument at index 35 because the index is out of range. The statement has 1 parameters.

arraylist 和 String[] 都必须有从索引 0 到 34 的 35 个元素

我不明白问题出在哪里?

您是否尝试将列 Util.KEY_TOPIC 与数组 idsArray 的项目进行匹配?
如果是这样,您不应使用运算符 =,而应使用运算符 IN 并构造方法 query()selection 参数,以便包含尽可能多的 ?占位符作为 idsArray.

的项目数

一个更简单的方法是创建一个包含 idsArray 的所有项目的逗号分隔列表,类似于 ",1,2,3"Arrays.toString():

String ids = Arrays.toString(idsArray).replaceAll("[\[\]]", ",").replace(" ", "");

并使用运算符 LIKE:

Cursor cursor = myDb.query(
    Util.TABLE_NAME,
    null,
    "? LIKE '%,' || " + Util.KEY_TOPIC + " || ',%'",
    new String[] {ids},
    null,
    null,
    null
);