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);
}
}
@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