2

I had the following code for Content Resolver Query:

String selection = Columns.NAME + "=? and " + Columns.AVAILABILITY + "=?";
String[] selectionArgs = { name, true };
Cursor c = getContentResolver().query(Columns.URI, null, selection, selectionArgs, null);

This code was working fine since I had only one name, but now I have an array of names which are to be added to cursor only if their availability is true. ie, my scenario is I want to put those rows in the cursor which have any of the names (present in the array) only if their Availability is true.

How can I achieve this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

8

SQL has the IN operator for this:

String selection = Columns.NAME + " IN (?,?,?) AND" +
                   Columns.Availability + " = ?";
String[] selectionArgs = { name[0], name[1], name[2], true };
...

If the array size is not predetermined, you have to construct the selection string and the selectionArgs array dynamically:

String selection = Columns.NAME + " IN (" + makePlaceholders(names.length) + ")" +
                   " AND " + Columns.Availability + " = ?";
String[] selectionArgs = new String[names.length + 1];
for (int i = 0; i < names.length; i++)
    selectionArgs[i] = names[i];
selectionArgs[names.length] = true;
...

with the function makePlaceholders copied from this answer:

String makePlaceholders(int len) {
    StringBuilder sb = new StringBuilder(len * 2 - 1);
    sb.append("?");
    for (int i = 1; i < len; i++)
        sb.append(",?");
    return sb.toString();
}
Community
  • 1
  • 1
CL.
  • 173,858
  • 17
  • 217
  • 259
  • Yes, the array size and values are not predetermined. can u please explain how can I do it now. – user1851261 May 13 '14 at 09:23
  • [Java: convert List to a join()d string](http://stackoverflow.com/questions/1751844/java-convert-liststring-to-a-joind-string); [How to add new elements to an array?](http://stackoverflow.com/questions/2843366/how-to-add-new-elements-to-an-array) – CL. May 13 '14 at 09:33
  • it's work with me, thank you <3 but I removed final line "selectionArgs[names.length] = true;" because it return an error – Haya Akkad Feb 16 '19 at 21:17