Search code examples
androidcontacts

how to query contact by a list of email addresses


Would like to get contacts from the device.

In the source code, the CONTENT_LOOKUP_URI is used for look up against one email. What about if I have a list of emails, and would like to query the contacts who are in this email list?

/**
         * <p>
         * The content:// style URL for looking up data rows by email address. The
         * lookup argument, an email address, should be passed as an additional path segment
         * after this URI.
         * </p>
         * <p>Example:
         * <pre>
         * Uri uri = Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(email));
         * Cursor c = getContentResolver().query(uri,
         *          new String[]{Email.CONTACT_ID, Email.DISPLAY_NAME, Email.DATA},
         *          null, null, null);
         * </pre>
         * </p>
         */
        public static final Uri CONTENT_LOOKUP_URI = Uri.withAppendedPath(CONTENT_URI,
                "lookup");

Solution

  • CONTENT_LOOKUP_URI works with the contacts column LOOKUP_KEY in case the contact's _id changes after sych. So if you have not stored this key somewhere the this uri is of no use to you. The usage of email as the key may or may not work depending on what is used as the look up key.

    If you did store the lookup key then this should be your query for a list of keys

    List<String> keys;
    for(String key : keys){
        Cursor cursor = getContentResolver().query(
            Uri.withAppendedPath(ContactsContract.CommonDataKinds.Email.CONTENT_LOOKUP_URI, "/" + key), 
            null, null, null, null);
    }
    

    If all you have are email addresses, then the best way to go would be

    List<String> emails;
    String[] questionMarks = new String[emails.size()];
    Arrays.fill(questionMarks,"?");
    Cursor cursor = getContentResolver().query(
            ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Email.DATA + " IN (" + TextUtils.join(",", questionMarks) + ")",
            emails.toArray(new String[emails.size()]), null);
    

    Be careful though when dealing with email addresses. Things like case and dots can be important and should be accounted for (when necessary) but if you don't fall into these cases, then the above method should work just fine. To ignore case just add COLLATE NOCASE to the selection arguments.