Android: Get Contact Details (ID, Name, Phone, Photo)


res/layout/main.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent" >

    <Button android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Select a Contact"
            android:onClick="onClickSelectContact" />

    <ImageView android:id="@+id/img_contact"
               android:layout_height="wrap_content"
               android:layout_width="match_parent"
               android:adjustViewBounds="true"
               android:contentDescription="Contacts Image"
                />

</LinearLayout>

MyActivity.java


package com.example;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;

public class MyActivity extends Activity {

    private static final String TAG = MyActivity.class.getSimpleName();
    private static final int REQUEST_CODE_PICK_CONTACTS = 1;
    private Uri uriContact;
    private String contactID;     // contacts unique ID


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onClickSelectContact(View btnSelectContact) {

        // using native contacts selection
        // Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
        startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
    }

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

        if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
            Log.d(TAG, "Response: " + data.toString());
            uriContact = data.getData();

            retrieveContactName();
            retrieveContactNumber();
            retrieveContactPhoto();

        }
    }

    private void retrieveContactPhoto() {

        Bitmap photo = null;

        try {
            InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
                    ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));

            if (inputStream != null) {
                photo = BitmapFactory.decodeStream(inputStream);
                ImageView imageView = (ImageView) findViewById(R.id.img_contact);
                imageView.setImageBitmap(photo);
            }

            assert inputStream != null;
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void retrieveContactNumber() {

        String contactNumber = null;

        // getting contacts ID
        Cursor cursorID = getContentResolver().query(uriContact,
                new String[]{ContactsContract.Contacts._ID},
                null, null, null);

        if (cursorID.moveToFirst()) {

            contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
        }

        cursorID.close();

        Log.d(TAG, "Contact ID: " + contactID);

        // Using the contact ID now we will get contact phone number
        Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                        ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                new String[]{contactID},
                null);

        if (cursorPhone.moveToFirst()) {
            contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }

        cursorPhone.close();

        Log.d(TAG, "Contact Phone Number: " + contactNumber);
    }

    private void retrieveContactName() {

        String contactName = null;

        // querying contact data store
        Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);

        if (cursor.moveToFirst()) {

            // DISPLAY_NAME	= The display name for the contact.
            // HAS_PHONE_NUMBER =	An indicator of whether this contact has at least one phone number.

            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }

        cursor.close();

        Log.d(TAG, "Contact Name: " + contactName);

    }
}

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8"/>

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

    <application android:label="@string/app_name">
        <activity android:name="MyActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest> 


get all the phone numbers + all the email address of a contact


ContentResolver contactResolver = context.getContentResolver();

Cursor cursor = contactResolver.query(Uri.parse(aContact.getLookupUri()), null, null, null, null);

if (cursor != null && cursor.moveToFirst()) {

    String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
    String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));

    if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
    {
        Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);

        while (pCur.moveToNext())
        {
            String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
            String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");


            Log.d("TAG", s + " phone: " + phone);
        }

        pCur.close();

    }

    Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);

        while (emailCursor.moveToNext())
        {
            String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");

            Log.d("TAG", s + " email: " + phone);
        }

    emailCursor.close();

    cursor.close();
}

Advertisements

20 thoughts on “Android: Get Contact Details (ID, Name, Phone, Photo)

  1. When I choose a contact without a number/with image the app works fine but when I choose a contact with a number/without image the app FC

  2. mentioned code as ‘get all the phone numbers + all the email address of a contact’ coming under MyActivity class?

  3. I know it’s probably bot the right way to o it but to help Jay and others I just removed the try statement changed it to else and used a pic from drawable just in case contact had no image.

  4. my main activity file……………………..
    …………………………
    listView = (ListView) findViewById(R.id.list);
    listView.setOnItemClickListener(this);

    Cursor phones = getContentResolver().query(
    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
    null, null);

    int number = phones.getColumnIndex(Phone.NUMBER);
    int name = phones.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
    int id = phones.getColumnIndex(Contacts.PHOTO_ID); // NEW LINE

    while (phones.moveToNext()) {

    // String phonename = phones
    // .getString(phones
    // .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    //
    // String phoneNumber = phones
    // .getString(phones
    // .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    // String image = phones
    // .getString(phones
    // .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID));
    String phName = phones.getString(name);
    String phNumber = phones.getString(number);

    long phId = phones.getLong(id);
    Bitmap image = loadContactPhoto(getContentResolver(), phId); // NEW LINE
    Log.d(“phId=”, phId + “”);

    ContactBean objContact = new ContactBean();
    objContact.setName(phName);
    objContact.setPhoneNo(phNumber);
    objContact.setImage(image);
    list.add(objContact);

    }
    phones.close();

  5. adapter file……
    ………………………………
    public ContanctAdapter(Activity act, int row, List items) {
    super(act, row, items);

    this.activity = act;
    this.row = row;
    this.items = items;

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    ViewHolder holder;
    if (view == null) {
    LayoutInflater inflater = (LayoutInflater) activity
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(row, null);

    holder = new ViewHolder();
    view.setTag(holder);
    } else {
    holder = (ViewHolder) view.getTag();
    }

    if ((items == null) || ((position + 1) > items.size()))
    return view;

    objBean = items.get(position);

    holder.tvname = (TextView) view.findViewById(R.id.tvname);
    holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
    holder.image=(ImageView)view.findViewById(R.id.image);

    if (holder.tvname != null && null != objBean.getName()
    && objBean.getName().trim().length() > 0) {
    holder.tvname.setText(Html.fromHtml(objBean.getName()));
    }
    if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
    && objBean.getPhoneNo().trim().length() > 0) {
    holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
    }
    if (holder.image != null && null != objBean.getImage()
    && objBean.getImage().toString().length() > 0) {
    //holder.image.setImageURI((Uri) Html.toHtml(objBean.getImage()));
    holder.image.setImageBitmap(objBean.getImage());
    }
    return view;
    }

    public class ViewHolder {
    public ImageView image;
    public TextView tvname, tvPhoneNo;
    }

    }

  6. App kill when I click on contact, which it havent image. I think this fail
    ” if (inputStream != null) {
    photo = BitmapFactory.decodeStream(inputStream);
    ImageView imageView = (ImageView) findViewById(R.id.img_contact);
    imageView.setImageBitmap(photo);
    }

    assert inputStream != null;
    inputStream.close();”
    But I dont know how to fix this. Pls have me

  7. i want only updated or deleted or added number from contact book to my app if user did change in contact not all contact

  8. I don’t know What is “aContact” in line 3 at: get all the phone numbers + all the email address of a contact. Could you tell me?

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