Android code for reading phone contacts detail

Here is code for reading all phone contacts(phone number,  email etc with their type) stored in android phone programmatically.

Code:
public static void getContacts(ContentResolver cr) {
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
    // read id
        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
        /** read names **/
        String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        /** Phone Numbers **/
            Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
            while (pCur.moveToNext()) {
                String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                String typeStr = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
        }
        pCur.close();
  /** EMAIL **/
  Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
  while (emailCur.moveToNext()) {
   String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
   String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
  }
  emailCur.close();

 }
}
}

Permission in AndroidManifest.xml: 
Add the READ_CONTACTS permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

5 comments:

  1. What is the variable that calls the search? What would I change in the code if I want to use a variable from a text box or recognizer?

    ReplyDelete
  2. @Ian, I think your question is not clear... What you are trying to refer by "the variable that calls the search"???


    If you are confused about how to call this function :
    the code presented above is static function which takes instance of ContentResolver as parameter.

    You can call it as :
    YourClassName.getContacts(instace_of_ContentResolver ).


    If you want to read the contact details of a particular person You can add parameter to this function and compare with the results to get more information.

    Thanks.

    ReplyDelete
  3. I understand but need example to test, can u provide please?

    ReplyDelete
  4. you can paste this code on any basic 'HelloWorld' type project class and call it from there.

    ReplyDelete

Your Comment and Question will help to make this blog better...