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:

Stringselection= 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:

Stringselection= Columns.NAME + " IN (" + makePlaceholders(names.length) + ")" +
                   " AND " + Columns.Availability + " = ?";
String[] selectionArgs = newString[names.length + 1];
for (inti=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) {
    StringBuildersb=newStringBuilder(len * 2 - 1);
    sb.append("?");
    for (inti=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"