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 = new HashMap<Long, List<String>>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.PHOTO_ID};
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1);
String mime = cur.getString(2); // email / phone / company
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
int type = cur.getInt(4); // a numeric value representing type: e.g. home / office / personal
String label = cur.getString(5); // a custom label in case type is "TYPE_CUSTOM"
long photoId = cur.getLong(6);
String kind = "unknown";
String labelStr = "";
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 = new ArrayList<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?"