Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android content provider query IN clause

Tags:

android

sqlite

Is possible to use an IN clause for a content provider?

I am currently using

cursor = contentResolver.query(CONTENT_URI, PROJECTION, "field IN (?)", new String[] { argsBuilder.toString() }, null);

If i remove the (?) and just use ? I get an error.

I get 0 count in my cursor.

If I type manually and execute the query in sqlite3 it works.

Help?

like image 366
dnkoutso Avatar asked Aug 10 '11 05:08

dnkoutso


2 Answers

When using the IN operator, you need to have one ? separated by a comma per argument you provide in your selectionArgs array. E.g.:

String[] selectionArgs = {"red", "black"};
String selection = "color IN (?, ?)";

The following picks the right count and the proper args:

int argcount = 2; // number of IN arguments
String[] args = new String[]{ 1, 2 };
StringBuilder inList = new StringBuilder(argcount * 2);
for (int i = 0; i < argcount; i++) { 
    if(i > 0) {
        inList.append(",");
    }
    inList.append("?"); 
}
cursor = contentResolver.query(
   CONTENT_URI, 
   PROJECTION, 
   "field IN (" + inList.toString() + ")", 
   args, 
   null);
like image 179
Femi Avatar answered Nov 02 '22 14:11

Femi


If your arguments are numbers only, this works as well:

Iterable args = ...; // any array, list, set, ... 
cursor = contentResolver.query(CONTENT_URI, PROJECTION, "field IN (" + TextUtils.join(",", args) + ")", null, null);
like image 21
saschoar Avatar answered Nov 02 '22 12:11

saschoar