Search code examples
javaandroidsqlsqliteandroid-sqlite

How to control where id is equal to unknown number of variable sql query?


I am looking for something like that:

String ID = ContactsContract.Contacts._ID;
ContentResolver cR = context.getContentResolver();
Cursor cursor = cR.query(mUri, null, ID + " =?", mStringArray, null);

mStringArray is not obvious, and the user will assign its elements. So we don't know what is the length of the array and what elements mStringArray has. I want to query for every values of mStringArray. In that case, i am getting an error which is "IllegalArgumentException: Cannot bind argument at index 2(or 3,4,...) because the index is out of range. The statement has 1 parameters".

I hope i am clear.


Solution

  • Instead of = you should use the operator IN and construct the statement with as many ? placeholders as the items of the array mStringArray:

    String ID = ContactsContract.Contacts._ID;
    ContentResolver cR = context.getContentResolver();
    
    StringBuilder sb = new StringBuilder();
    for (String s : mStringArray ) {
        sb.append("?,");
    }
    String sqlIn = null;
    if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1);
        sqlIn = ID + " IN (" + sb.toString() + ")";
    }
    Cursor cursor = cR.query(mUri, null, sqlIn, mStringArray, null);