Skip to content Skip to sidebar Skip to footer

Android:SQLite - Querying An Array In SelectionArgs As Well As Other String Values

I had the following code for Content Resolver Query: String selection = Columns.NAME + '=? and ' + Columns.AVAILABILITY + '=?'; String[] selectionArgs = { name, true }; Cursor c =

Solution 1:

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();
}

Post a Comment for "Android:SQLite - Querying An Array In SelectionArgs As Well As Other String Values"