Skip to content Skip to sidebar Skip to footer

How To Fetch All Contacts From Local Phonebook And Google Contacts Together?

I am trying to fetch contacts from the phonebook in my Android application. But it fetches the contacts that are present only in the local phone storage. I need to fetch all the co

Solution 1:

Your code should work on all contacts synced to the device, including Google contacts (assuming the Google account is installed, and the contacts sync is enabled).

However, your code has some bugs, and can be greatly improved, currently for a device with 500 contacts, you are doing ~1000 queries. All the data you need is on a single table called Data so you can get everything in a single quick query, see here:

Map<Long, Contact> contacts = newHashMap<>();

String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1};
Stringselection= Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "')";
Cursorcur= cr.query(Data.CONTENT_URI, projection, selection, null, null);

while (cur.moveToNext()) {
    longid= cur.getLong(0);
    Stringname= cur.getString(1);
    Stringmime= cur.getString(2); // email / phoneStringdata= cur.getString(3); // the actual info, e.g. +1-212-555-1234// get the Contact class from the HashMap, or create a new one and add it to the Hash
    Contact contact;
    if (contacts.containsKey(id)) {
        contact = contacts.get(id);
    } else {
        contact = newContact(id);
        contact.setDisplayName(name);
        // start with empty Sets for phones and emails
        contact.setPhoneNumbers(newHashSet<>());
        contact.setEmails(newHashSet<>());
        contacts.put(id, contact);
    } 

    switch (mime) {
        case Phone.CONTENT_ITEM_TYPE: 
            contact.getPhoneNumbers().add(data);
            break;
        case Email.CONTENT_ITEM_TYPE: 
            contact.getEmails().add(data);
            break;
    }
}
cur.close();

Notes:

  1. I've changed your listContacts to a HashMap called contacts so we can quickly find an existing contact
  2. I've added setEmails, getPhoneNumbers and getEmails to your Contact class

Post a Comment for "How To Fetch All Contacts From Local Phonebook And Google Contacts Together?"