Search code examples
javaandroidsqlsqliteandroid-sqlite

query sqlite database has outofboundException


I have an ArrayList which I try to convert to String[] so I can query my database but I get outofboundException and I don't know where is the problem?

to convert arraylist to string[] :

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

then I use Cursor to query:

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

and this is how cursor loops:

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

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

and on the line that I give it idsArray I have this exception:

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

both arraylist and String[] must have 35 elements from index 0 to 34

I don't understand where is the problem?


Solution

  • Are you trying to match the column Util.KEY_TOPIC against the items of the array idsArray?
    If so, you should not use the operator = but the operator IN and construct the selection argument of the method query() so that is contains as many ? placeholders as the number of items of idsArray.

    An easier way to do this is to create a comma separated list of all the items of idsArray, something like ",1,2,3" with Arrays.toString():

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

    and use the operator LIKE:

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