Reputation: 21
I need fetch information from all Android contacts:
If the contact has two or more Cell phone numbers, it has to fit in the selection multiple times.
Now I use ContentResolver.Query()
to get the required columns, but need more than once queries, rather than join tables.
How can I query multiple data fields from Android contacts?
I.e. i need execute something like SQL query:
SELECT
dName.Data2 as [firstName]
, dName.Data3 as [lastName]
, dPhone.Data1 as [cellPhone]
FROM
raw_contacts
INNER JOIN data as dName on dName.RAW_CONTACT_ID = Contacts._ID and dName.MIME_TYPE = ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
INNER JOIN data as dPhone on dName.RAW_CONTACT_ID = Contacts._ID and dName.MIME_TYPE = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
Upvotes: 2
Views: 473
Reputation: 28169
All the fields you've mentioned are eventually stored in the ContactsContract.Data
table, so no need for joins.
You just need to query all the data in Data table, while selecting your specific mimetypes (phone and event, which is birthdays), the full contact-name and contact-id, are stored for each mimetype as well:
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};
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Event.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); // full name
String mime = cur.getString(2); // phone / birthday
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
String kind = "unknown";
switch (mime) {
case Phone.CONTENT_ITEM_TYPE:
kind = "phone";
break;
case Email.CONTENT_ITEM_TYPE:
Event = "birthday";
break;
}
Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data);
// 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);
contacts.put(id, infos);
}
infos.add(kind + " = " + data);
}
Upvotes: 1