1

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?

6
  • it means that index 35 in your array doesn't exist. Ergo you don't have enough items in your array and you are calling something that doesn't exist. Commented Nov 7, 2020 at 10:17
  • edit your question and post the entire stack trace (see logcat) The statement has 1 parameters. means that your query statement contains only one ? character. Commented Nov 7, 2020 at 10:19
  • I know but how can I make my cursor to don't call index 35? Commented Nov 7, 2020 at 10:20
  • I've added the cursor looping function Commented Nov 7, 2020 at 10:25
  • index 35 means its asking for a 36th element Commented Nov 7, 2020 at 10:27

1 Answer 1

1

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 ); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.