Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContentResolver and "IN" statement in "where" condition

Tags:

java

android

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

like image 244
Anarion Avatar asked Mar 19 '23 13:03

Anarion


1 Answers

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;
    }
like image 89
Larry McKenzie Avatar answered Apr 02 '23 10:04

Larry McKenzie