Showing posts with label ContactsContract. Show all posts
Showing posts with label ContactsContract. Show all posts

Tuesday, April 23, 2013

Android how to use ContactsContract to retrieve phone numbers and email addresses

ContactsContract is the contract between a contacts provider and applications 
that want to use contacts. The following code shows how to find a contact based on 
name, and once it's found, how to retrieve the various types of phone numbers and 
email addresses:
 
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;  
 
String NAME = "Pritom Mondal";
Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
 String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
 Cursor phones = managedQuery(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contactId, null, null);
 while (phones.moveToNext()) {
  String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
  int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
  System.out.println("TYPE: "+type+" NUMBER: "+number);
 }
 phones.close();
 
 Cursor emails = managedQuery(Email.CONTENT_URI, null, Email.CONTACT_ID + " = " + contactId, null, null);
 while (emails.moveToNext()) {
  String number = emails.getString(emails.getColumnIndex(Email.DATA));
  int type = emails.getInt(emails.getColumnIndex(Phone.TYPE));
  System.out.println("TYPE: "+type+" EMAIL: "+number);
 }
 emails.close();
}
cursor.close();