Skip to content Skip to sidebar Skip to footer

How To Retrieve All Contacts Details From Content Provider With Single Query?

I need to read the contacts from device. The fields I required are ID , Display Name, Phone Number (All types) Email id (All types) and 'photo'. For this right now I am doing like

Solution 1:

Yes, you can do that in a single query - all the data about contacts is actually stored in a single table Data, which contains everything you need on a contact including CONTACT_ID and DISPLAY_NAME which are also hosted on the Contacts table.

So you need to basically query everything from the Data table in a single query, and sort it out into contacts using a HashMap from CONTACT_ID to some contact object (or if you prefer a list of details).

(Note: make sure you import the following classes from ContactsContract package only)

Map<Long, List<String>> contacts = newHashMap<Long, List<String>>();

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

while (cur != null && cur.moveToNext()) {
    longid= cur.getLong(0);
    Stringname= cur.getString(1);
    Stringmime= cur.getString(2); // email / phone / companyStringdata= cur.getString(3); // the actual info, e.g. +1-212-555-1234inttype= cur.getInt(4); // a numeric value representing type: e.g. home / office / personalStringlabel= cur.getString(5); // a custom label in case type is "TYPE_CUSTOM"longphotoId= cur.getLong(6);

    Stringkind="unknown";
    StringlabelStr="";

    switch (mime) {
        case Phone.CONTENT_ITEM_TYPE: 
            kind = "phone"; 
            labelStr = Phone.getTypeLabel(getResources(), type, label);
            break;
        case Email.CONTENT_ITEM_TYPE: 
            kind = "email";
            labelStr = Email.getTypeLabel(getResources(), type, label);
            break;
    }
    Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data + " (" + labelStr + ")");

    // add info to existing list if this contact-id was already found, or create a new list in case it's new
    List<String> infos;
    if (contacts.containsKey(id)) {
        infos = contacts.get(id);
    } else {
        infos = newArrayList<String>();
        infos.add("name = " + name);
        infos.add("photo = " + photoId);
        contacts.put(id, infos);
    }
    infos.add(kind + " = " + data + " (" + labelStr + ")");
}

Post a Comment for "How To Retrieve All Contacts Details From Content Provider With Single Query?"