1

I have encountered this problem:

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

As a result of:

String where = "id_1 = 50 AND id_2 = ?";
//The String[] is ideally of dynamic length and not necessarily 3 in size.
String[] whereArgs = {"60", "61", "62"};

cursor.setSelection(where);
cursor.setSelectionArgs(whereArgs);

I am simply using it the wrong way. I have realized this already. But I would think it makes it evident what I am trying to accomplish.

My question: Is there a way for me to insert an array of varying length and arguments into a single parameter? Any best practices that I have missed. Have I simply baked myself into a bad situation?

The SQL statement I could be looking for:

WHERE id_1 = 50 AND ((id_2 = 60) OR (id_2 = 61) OR (id_2 = 62))

The only way I can think of to fix my problem is to create a string and build upon it in a loop the length of String[] adding OR (id_2 = xx) with every iteration. It just doesn't sound like a very good solution to me.

Thanks for your time!

Dennis
  • 169
  • 9

2 Answers2

1

In general, constructing the WHERE clause dynamically is the correct solution. Use StringBuilder.append() rather than + to save some string construction overhead.

In some cases, you may also want just issue multiple statements. So instead of

select from table where id_1 = 50 AND (id_2 = ? OR id_2 = ? OR id_2 = ?);

You could do a Batch of

select from table where id_1 = 50 AND (id_2 = ?);
select from table where id_1 = 50 AND (id_2 = ?);
select from table where id_1 = 50 AND (id_2 = ?);
ykaganovich
  • 14,736
  • 8
  • 59
  • 96
0

Try with this code:

String where = "id_1 = 50 AND (id_2 = ? OR id_2 = ? OR id_2 = ?)";

String[] whereArgs = {"60", "61", "62"};
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
Arnab Dhar
  • 239
  • 2
  • 15