Hi,
I'm a Android dev by hobby so bare with me if I'm not that elegant with this code.
You can loop through your phone contacts like this:
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know have the number so now query it like this
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
Cursor emails = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,
null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(
ContactsContract.CommonDataKinds.CommonDataColumns.DATA));
}
emails.close();
}
cursor.close();
Additionally, you can loop through your contacts and simply get the name and phone number like this:
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String number = people.getString(nameFieldColumnIndex);
}
people.close();
Furthermore, if you need to get things like notes from a contact then you will need to use a different URI, like the following (feel free to use this method):
private String getNote(long contactId) {
String note = null;
String[] columns = new String[]
{ ContactsContract.CommonDataKinds.Note.NOTE };
String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{Long.toString(contactId),
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor contacts = getContentResolver().query
(ContactsContract.Data.CONTENT_URI, projection, where,
whereParameters, null);
if (contacts.moveToFirst()) {
rv = contacts.getString(0);
}
contacts.close();
return note;
}
Notice this time I used not only the contact id but the mime type for the query.
Android FTW!