Wednesday, June 13, 2012

Query Contacts data

Query on Contacts content provider

1)
Create a Uri using ContactsContract.Contacts.CONTENT_URI and query with the Uri...

Uri myPerson=ContactsContract.Contacts.CONTENT_URI;
Cursor cur=managedQuery(myPerson, null, null, null, null);

2) Example of query phone numbers of contacts.

if (cur.moveToFirst()) {
String name;
String contactId;
int nameColumn = cur.
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID);
do {
name = cur.getString(nameColumn);
contactId = cur.getString(idColumn);
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));

System.out.println("name=" + name + " phoneNumber="+ phoneNumber);
}
phones.close();
} while (cur.moveToNext());
}