Search code examples
androidandroid-contactsandroid-cursorcontactscontract

ContactsContract select records by phone number


I can select all contacts using the query below

    cr = mActivity.getContentResolver();
    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0";
    String orderBy = ContactsContract.Contacts.DISPLAY_NAME + " ASC ";
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, selection, null, orderBy);

However, I have a phone number list and I want to create this query like

String selection = ContactsContract.Contacts.PhoneNumber_or_something_else  in (MyPhoneNumberArray)

Is that possible to do this?

A worst-case scenario, I can remove the related item using do while after I create my cursor, but, as far as I know, I cannot remove any record from the cursor.


Solution

  • The Contacts DB is organized in three main tables:

    1. Contacts - each entry represents one contact, and groups together one or more RawContacts
    2. RawContacts - each entry represents data about a contact that was synced in by some SyncAdapter (e.g. Whatsapp, Google, Facebook, Viber), this groups multiple Data entries
    3. Data - The actual data about a contact, emails, phones, etc. each line is a single piece of data that belongs to a single RawContact

    All phone numbers in the Contacts DB are in the Data table, so that's what you need to query, you can get the list of CONTACT_IDs from that query and use it to get general info about contacts if you need.

    String[] phonesList = new String[] { "+121212345" }; // will work better if all phones in this list are in e164 format
    
    String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone.NORMALIZED_NUMBER };
    String selection = Phone.NUMBER + " IN ('" + TextUtils.join("','", phonesList) + "') OR " + 
                       Phone.NORMALIZED_NUMBER + " IN ('" + TextUtils.join("','", phonesList) + "')";
    Cursor cur = cr.query(Phone.CONTENT_URI, projection, selection, null, null);
    
    while (cur != null && cur.moveToNext()) {
        long id = cur.getLong(0);
        String name = cur.getString(1);
        String phone = cur.getString(2);
        Log.d(TAG, "got " + id + ", " + name + ", " + phone;
    }