Skip to content

Instantly share code, notes, and snippets.

@evandrix
Created October 19, 2013 16:39
Show Gist options
  • Save evandrix/7058235 to your computer and use it in GitHub Desktop.
Save evandrix/7058235 to your computer and use it in GitHub Desktop.
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);
}
}
@bwmusake
Copy link

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
Copy link

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
Copy link

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
Copy link

Thanks!

@NicolasABC
Copy link

NicolasABC 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
Copy link

aamrin 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
Copy link

Thank you so much !!!

@ZAHRAA26
Copy link

ZAHRAA26 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
Copy link

aamrin 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
Copy link

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

@Ncastro878
Copy link

This has been very helpful. Thanks alot!

@lihongzhan
Copy link

Thank you,it's very useful!

@thetechnerdrohit
Copy link

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

@NandaShetty
Copy link

Thank you so much ,it was very help full!

@tomerpetel
Copy link

Thx! much appreciated!

@Sajjad5989
Copy link

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

@bibin-johny
Copy link

Thanks , Really useful..

@SteveOye
Copy link

Thanks, you saved me after two days of misery

@saadh393
Copy link

Thanks a lot.

@overlord-cyber
Copy link

how can i get the email and birthday from contact

@chnouman
Copy link

chnouman commented Aug 6, 2020

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();

}`

not working.

@TRIJIT-BHATTACHARJEE
Copy link

Unfortunately, app has stopped.

Copy link

ghost commented Nov 28, 2020

hello,
Your code is very useful and I've used it
but the main problem in this ,it doesnt take permission so please add permission code
` public void onClickSelectContact(View btnSelectContact) {

    // using native contacts selection
    // Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
     if(!hasPhoneContactsPermission(Manifest.permission.READ_CONTACTS))
     {
                requestPermission(Manifest.permission.READ_CONTACTS);
       }else {
          startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
      }
}

// Check whether user has phone contacts manipulation permission or not.
private boolean hasPhoneContactsPermission(String permission) {
/*boolean ret = false;
// If android sdk version is bigger than 23 the need to check run time permission.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        // return phone read contacts permission grant status.
        int hasPermission = ContextCompat.checkSelfPermission(getApplicationContext(), permission);
        // If permission is granted then return true.
        if (hasPermission == PackageManager.PERMISSION_GRANTED) {
            ret = true;
        }
    }else
    {
        ret = true;
    }
    return ret;*/
    boolean returnValue=false;
    // If android sdk version is bigger than 23 the need to check run time permission.
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
        int hasPermission= ContextCompat.checkSelfPermission(getApplicationContext(),permission);
        if(hasPermission==PackageManager.PERMISSION_GRANTED){
            returnValue=true;
        }
    }
    return returnValue;
}

// Request a runtime permission to app user.
private void requestPermission(String permission) {
    String requestPermissionArray[] = {permission};
    ActivityCompat.requestPermissions(this, requestPermissionArray, 1);
}

// After user select Allow or Deny button in request runtime permission dialog
// , this method will be invoked.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    int length = grantResults.length;
    if(length > 0)
    {
        int grantResult = grantResults[0];

        if(grantResult == PackageManager.PERMISSION_GRANTED) {

            Toast.makeText(getApplicationContext(), "You allowed permission, please click the button again.", Toast.LENGTH_LONG).show();
        }else
        {
            Toast.makeText(getApplicationContext(), "You denied permission.", Toast.LENGTH_LONG).show();
        }
    }
}

`

@sembapur
Copy link

thx bro, mantap jaya!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment