Thursday, November 24, 2011

How to call Android contact list

1) Add the following to your AndroidManifest:

<uses-permission android:name="android.permission.READ_CONTACTS">

2) Call the Contact Picker from your activity by using the following intent:

Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, CHOOSE_CONTACT);

3) get the phone through the contact id; you will need to query the contentResolver twice

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  switch (requestCode) {
    case (CHOOSE_CONTACT):
    if (resultCode == Activity.RESULT_OK) {
        Uri contactInfo = data.getData();
        Cursor c = managedQuery(contactInfo, null, null, null, null);
        if (c.moveToFirst()) {
                String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String hasPhone = c.getString(c.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String phoneNumber = "";
                if (hasPhone != null &amp;&amp; hasPhone.equalsIgnoreCase("1")) {
                        Cursor phones = getContentResolver()
                                .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,                                                            
                                           ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                           + " = " + contactId, null, null);

                               while (phones.moveToNext()) {
                                        phoneNumber = phones.getString(phones
                                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                               }
                       phones.close();
               }

               // do something with the name and phone; you can also accesss other information such as photo
        }
    }
    break;
  }
}

1 comment:

  1. find out downloadable source from below link

    http://tutorials-android.blogspot.in/2011/06/create-your-own-custom-keyboard-for.html

    ReplyDelete