Android Programming: Reading Contact numbers and Email Addresses


Suppose we want to read all the contact numbers and their email IDs stored in the user’s address book.

I have written below method that will read all the contact numbers along with the email address and will display them in the EditText control.

To do so, in the below method, I have written two cursors. First cursor will read all the information related to phone contacts table. In the phone contacts table Contact_ID is the primary key. Second cursor will read all the information related to Emails based on the Contact_ID fetched from the first cursor. Contact_ID is also unique in the Email data. In short, Contact_ID is common unique column in the both the tables.

 

 public void GetMobileNumberAndEmail()
 {
  String strId=null;
  String pID="";
  TextView txtvw = (TextView) findViewById(R.id.tvDemo);
  ContentResolver cr = getContentResolver();
  Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " Asc");
  if (cur.getCount()>0)
  {
   while (cur.moveToNext())
   {
    strId = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));


    if (pID.compareTo(strId)!=0)
    {
     Cursor EmailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "= ?", new String[] { strId }, null);

     txtvw.append("-----------------------------\n");
     txtvw.append("\nName-->" + cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)) + "\n");
     txtvw.append("\nMobile-->" + cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) + "\n");

    if (EmailCur.getCount()>0)
    {
     while (EmailCur.moveToNext())
     {
      txtvw.append("\nEMail ID-->" + EmailCur.getString(EmailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)) + "\n");
     }

    EmailCur.close();
    }
    } else
     {
      txtvw.append("\nMobile-->" + cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) + "\n");
      txtvw.append("-----------------------------\n");
     }
    pID=strId;
   }
    cur.close();
  }
 }

 

Result:

 

clip_image002

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s