Reputation: 2534
I am trying to get cursor for a list of contacts based on therir ids. I am not really sure how to use "IN" statement with an array of arguments. What I currently have causes an error.
public Cursor GetContacts(String[] ids)
{
ContentResolver cr = getContentResolver();
try
{
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
String where = ContactsContract.Contacts._ID + " IN ?";
String[] selectionArgs = ids;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
return cr.query(uri, projection, where, selectionArgs, sortOrder);
}
catch (Exception ex)
{
String message = ex.getMessage();
Log.e("mine", "Error: " + message, ex);
return null;
}
Error: near "?": syntax error (code 1): , while compiling: SELECT _id, display_name, has_phone_number FROM view_contacts WHERE ((1)) AND ((_id IN ?)) ORDER BY display_name
Upvotes: 4
Views: 2264
Reputation: 7557
We can add selectionArguments in where part itself
public Cursor getCursor() {
Uri contentUri = Uri.withAppendedPath(ContentProviderDb.CONTENT_URI, TABLE_FEEDS);
String feedList = "27","79","78","77","31";
String where = FEED_ID + " IN ("+feedList+") AND " + PLACE_ID + "=\"" +placeId+"\" AND " + PROFILE_ID + "=" + userId ;
return context.getContentResolver().query(contentUri, null, where, null, TIMESTAMP + " DESC");
}
Here If the selection argument value is String need to add escape character.
Upvotes: 0
Reputation: 3283
I didn't test this but I think you need to condense your ids into a single comma separated string in order to insert it into your query.
public Cursor GetContacts(String[] ids)
{
ContentResolver cr = getContentResolver();
try
{
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
String where = ContactsContract.Contacts._ID + " IN (?)";
String[] selectionArgs = {StringUtils.join(ids, ", ")};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
return cr.query(uri, projection, where, selectionArgs, sortOrder);
}
catch (Exception ex)
{
String message = ex.getMessage();
Log.e("mine", "Error: " + message, ex);
return null;
}
Upvotes: 7