Search code examples
androidandroid-contactscontactscontract

How to retrieve every possible contact?


There is multiple examples of how we could retrieve contacts in android the most common type is using ContactsContract like this:

ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.contacts.CONTENT_URI,null,null,null,null);

while(cursor.moveToNext){
//get contact details
.........

}

My Question:

If users can save their contacts in three places phone, SIM, google_account. Then how I am able to use a method that retrieves all numbers that a user have on the phone?

Also as the contact list in the phone duplicates contacts how can we avoid getting a contact twice or 4 times or 5 times?

What would be the method that one must use to cover all possible contacts once?


Solution

  • Users can actually save contacts in many places, not just 3, e.g. if a user installs the Yahoo app, they can start storing contacts on Yahoo as well, same goes for Outlook, etc.

    The ContactsContract covers all these options, and provides a single API to query for all contacts stored on the device. The different storage types are distinguished by ACCOUNT_NAME and ACCOUNT_TYPE at the RawContact level.

    a Contact result you get from your query, is actually an aggregation of multiple RawContacts coming from one or more origins or ACCOUNT_TYPEs, so duplicate RawContacts on your SIM and Phone should aggregate into a single Contact

    Here's some code to explore your own contacts on your device (this is very slow code, there are ways to improve performance significantly):

    String[] projection = new String[] { Contacts._ID, Contacts.DISPLAY_NAME};
    Cursor contacts = resolver.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
    
    while (contacts.moveToNext()) {
    
        long contactId = contacts.getLong(0);
        String name = contacts.getString(1);
    
        Log.i("Contacts", "Contact " + contactId + " " + name + " - has the following raw-contacts:");
    
        String[] projection2 = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_NAME };
        Cursor raws = resolver.query(RawContacts.CONTENT_URI, null, RawContacts.CONTACT_ID, null, null);
    
        while (raws.moveToNext()) {
    
            long rawId = raws.getLong(0);
            String accountType = raws.getString(1);
            String accountName = raws.getString(2);
    
            Log.i("Contacts", "\t RawContact " + rawId + " from " + accountType + " / " + accountName);
        }
        raws.close();
    }
    contacts.close();