Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android: Get Contact Details (ID, Name, Phone, Photo) @ http://tausiq.wordpress.com/2012/08/23/android-get-contact-details-id-name-phone-photo
<?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>
<?xml version="1.0" encoding="utf-8"?>
<!-- @res/layout/main.xml -->
<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>
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);
}
}
@blenyo

This comment has been minimized.

Copy link

commented Dec 19, 2014

This saved my day. Thanks a million times

@engr-erum

This comment has been minimized.

Copy link

commented Jan 28, 2015

how can i find contact email id of selected contact ?

@NabilNish

This comment has been minimized.

Copy link

commented Feb 20, 2015

Thank u!!!!!!!

@steff-maya

This comment has been minimized.

Copy link

commented Mar 22, 2015

Thanks .

@gaur12

This comment has been minimized.

Copy link

commented May 10, 2015

Thanx a lot man....
seriously, thanx man

@kamleshTelogo

This comment has been minimized.

Copy link

commented Sep 14, 2015

Thanks Sir...

@grennis

This comment has been minimized.

Copy link

commented Sep 18, 2015

Instead of querying for the contact ID, you can just call uri.getLastPathSegment()

@jobala

This comment has been minimized.

Copy link

commented Sep 24, 2015

Saved my life.

@devAseemSharma

This comment has been minimized.

Copy link

commented Oct 29, 2015

This is returning wrong result, name is correct but number is picked up of some other contact. I don't know why.

@devAseemSharma

This comment has been minimized.

Copy link

commented Oct 29, 2015

My issue was somewhat different, I was using Multiple number display, for that, we need to pass out contact URI which is obtained at onActivityResult, in this into content resolver, like this.:

Cursor cursorPhone = getContentResolver().query(uriContact,
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);

thanks for the post 👍

@prasannait10

This comment has been minimized.

Copy link

commented Nov 12, 2015

nice job man

@dannogo

This comment has been minimized.

Copy link

commented Nov 13, 2015

Very helpful. Thank you!

@orrinLife360

This comment has been minimized.

Copy link

commented Nov 13, 2015

Thanks for the writeup. Do you know if it is more efficient to query the phone, email, and other data individually or is it faster to when getting a list of contacts or is using with a projection that includes the needed fields using http://developer.android.com/reference/android/provider/ContactsContract.Data.html ?

@harsha8287

This comment has been minimized.

Copy link

commented Dec 14, 2015

very helpful. How to compare the contacts in database and native device contacts and display only registered app user contact list??

@abbath0767

This comment has been minimized.

Copy link

commented Apr 15, 2016

thank you! but this works only api < 23

@dmsherazi

This comment has been minimized.

Copy link

commented May 8, 2016

what if the contact has more than one phone number?

@AravindMJ

This comment has been minimized.

Copy link

commented Jul 6, 2016

Very helpful!

@samirsamedov

This comment has been minimized.

Copy link

commented Aug 8, 2016

That was very usefull thanks.

@bnovakovic

This comment has been minimized.

Copy link

commented Nov 17, 2016

In case anyone needs to get multiple numbers from same contact:

`
private void retrieveContactNumbers() {

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

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

    cursorID.close();

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

            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                    ContactsContract.CommonDataKinds.Phone.TYPE_HOME +
                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE +
                    ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK +
                    ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME +
                    ContactsContract.CommonDataKinds.Phone.TYPE_PAGER +
                    ContactsContract.CommonDataKinds.Phone.TYPE_OTHER +
                    ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK +
                    ContactsContract.CommonDataKinds.Phone.TYPE_CAR +
                    ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN +
                    ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX +
                    ContactsContract.CommonDataKinds.Phone.TYPE_RADIO +
                    ContactsContract.CommonDataKinds.Phone.TYPE_TELEX +
                    ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD +
                    ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE +
                    ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER +
                    ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT +
                    ContactsContract.CommonDataKinds.Phone.TYPE_MMS,

            new String[]{contactID},
            null);

    while (cursorPhone.moveToNext()){
        contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
         Log.d(TAG, "Contact Phone Number: " + contactNumber);
    }
    cursorPhone.close();

}`
@praviinz

This comment has been minimized.

Copy link

commented Jan 14, 2017

suppose i hv button select all
how do i select all contact

@bwmusake

This comment has been minimized.

Copy link

commented Jan 21, 2017

I have looked at this code for a long time trying to see where uriContact gets assigned, and I can't find it, can someone please point me to the right direction as to what exactly am missing

@bwmusake

This comment has been minimized.

Copy link

commented Jan 21, 2017

Am basically asking what is the value of Uri uriContact, when it is used in the query statement as I cannot find the instance it is getting assigned to a value, tho has been used. Thank you

@nagarjsr50

This comment has been minimized.

Copy link

commented Feb 17, 2017

I did factory reset of my Lenova K6 power powered by Android ver.6.0.1 without saving my contacts about 1100nos.
I need to recover them.Is it possible?If so pls help me.

@pinakjoshi

This comment has been minimized.

Copy link

commented Apr 6, 2017

Thanks!

@NicolasABC

This comment has been minimized.

Copy link

commented Jul 6, 2017

Hi, can anyone help on why this keeps crashing when I try to retrieve the phone number of a contact please? I've tried multiple ways but it just doesn't seem to work. Not sure if the problem is in the declaration of the cursor?

public class MainActivity extends Activity {

private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private Uri uriContact;
private String contactID;     // contacts unique ID

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void onClickSelectContact(View btnSelectContact) {
    startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
    Log.d("PROGRESSCHECK", "starting ActivityForResult");
}

@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("PROGRESSCHECK", "Response: " + data.toString());
        uriContact = data.getData();

        retrieveContactNumber();
    }
}

private void retrieveContactNumber() {

    String contactNumber;
    String contactEmail = 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("PROGRESSCHECK", "Contact ID: " + contactID);

    Cursor cursorPhone = getContentResolver().query(uriContact, null, null, null, null);

    while (cursorPhone.moveToNext()) {
        Integer hasPhoneNumber = null;
        hasPhoneNumber = Integer.parseInt(cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
        Log.d("PROGRESSCHECK", "hasPhoneNumber = " + hasPhoneNumber);

        if (hasPhoneNumber > 0){
            String DisplayName = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            Log.d("PROGRESSCHECK", "Display Name = " + DisplayName);
            
            contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.d("PROGRESSCHECK", "contactNumber = " + contactNumber);
        } else{
            Log.d("PROGRESSCHECK", "No Phone number");
        }
    }

    cursorPhone.close();

}

@aamrin

This comment has been minimized.

Copy link

commented Jul 10, 2017

hello, when I run this app it shows me unfortunately stop how i solve this error please reply as soon as possible and help me

@pierre225

This comment has been minimized.

Copy link

commented Jul 12, 2017

Thank you so much !!!

@ZAHRAA26

This comment has been minimized.

Copy link

commented Jul 14, 2017

@aamrin
when it doesn't make with you you can add read_contacts permission in manifest file

i found filter result from logcat file that APP can't read contacts.
show this for more information
https://stackoverflow.com/questions/19931987/how-to-filter-logcat-in-android-studio/19948588#19948588

@aamrin

This comment has been minimized.

Copy link

commented Jul 15, 2017

when I click on button and click on any contact t it show unfortunately stop please help me to sort out and reply soon as possible

@garganshu

This comment has been minimized.

Copy link

commented Nov 7, 2017

Add runtime permission if using marshmallow.
The app will crash if the runtime permission check is not added

@Ncastro878

This comment has been minimized.

Copy link

commented Dec 8, 2017

This has been very helpful. Thanks alot!

@lihongzhan

This comment has been minimized.

Copy link

commented Jan 11, 2018

Thank you,it's very useful!

@rohit2311

This comment has been minimized.

Copy link

commented Jan 11, 2018

what should i do if i wanna select multiple contact plzz help me plzzzz

@NandaShetty

This comment has been minimized.

Copy link

commented Jan 12, 2018

Thank you so much ,it was very help full!

@tomerpetel

This comment has been minimized.

Copy link

commented Jan 21, 2018

Thx! much appreciated!

@Sajjad5989

This comment has been minimized.

Copy link

commented Jan 31, 2018

Hello
Thank you very much
## Your code is very useful and I've used it
I hope you have more success

@bibin-johny

This comment has been minimized.

Copy link

commented Aug 24, 2018

Thanks , Really useful..

@SteveOye

This comment has been minimized.

Copy link

commented Jun 14, 2019

Thanks, you saved me after two days of misery

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.