Get Contact Photo based on Contact PhoneNumber And

2019-02-09 11:51发布

问题:

Android 2.3.3

I have looked at various examples on how to get "Photo of a Contact". But none of them worked for me. Surprisingly, I have stumbled upon a code at StackOVerFlow and I used it and could get the "Photo" and display it in ImageView in my ListView.

Scenario of my application :::

I have to get data from Phone (Image / Photo, Contact Name, Phone Number) and display them in a ListView (with CustomView as each Item)

XML File with ListView :::

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

<TextView
     android:id="@+id/txtViewContactsHeader"
     android:layout_width="wrap_content"
     android:layout_height="50dp"
     android:text="Your Contacts (Phone + SIM)"
     android:layout_gravity="center"
     android:gravity="center" />


 <ListView
     android:id="@+id/lv_addcontact"
     android:layout_width="match_parent"
     android:layout_height="0dip"
     android:layout_weight="1" >

</ListView>

 <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="50dp"
     android:orientation="horizontal"
     android:layout_gravity="center"
     android:gravity="center" >

     <Button
         android:id="@+id/btn_addcontact_add"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="ADD CONTACTS" />

     <Button
         android:id="@+id/btn_addcontact_cancel"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="CANCEL" />

 </LinearLayout>

  <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="100dp"
     android:orientation="vertical" >

     <TextView
     android:id="@+id/txtViewNavigation"
     android:layout_width="wrap_content"
     android:layout_height="match_parent"
     android:text="Navigation"
     android:layout_gravity="center"
     android:gravity="center" />

 </LinearLayout>

XML File for Each ListView Item - CustomView :::

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="2dp"    
android:orientation="horizontal" >

<ImageView
    android:id="@+id/imgView_addcontact"
    android:layout_width="0dip"
    android:layout_height="100dp"
    android:layout_weight="0.20"
    android:padding="5dp"
    android:src="@drawable/addcontactsmall2" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="100dp"
    android:layout_gravity="center"
    android:layout_weight="0.60"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:id="@+id/txtView_addcontact_contactname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Contact Name"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/txtview_addcontact_phonenumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone Number"
        android:textSize="16sp" />
</LinearLayout>

<CheckBox
    android:id="@+id/chbk_addcontact"
    android:layout_width="0dp"
    android:layout_height="100dp"
    android:layout_weight="0.10"
    android:layout_gravity="center"
    android:padding="5dp" />

Java File - Code :::

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.PhoneLookup;

import android.provider.ContactsContract.Data;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Class_Add_Contact extends Activity {

    ListView lv_addcontacts;
    Cursor cur;
    ContentResolver cr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_add_contact);
        readContacts();

        if (!((cur.moveToFirst()) || cur.equals(null) || cur.getCount() == 0)) {

        } else if (cur.getCount() > 0) {
            cur.moveToFirst();
        }

        lv_addcontacts = (ListView) findViewById(R.id.lv_addcontact);

        CustomAdapterAddContacts myad = new CustomAdapterAddContacts();

        lv_addcontacts.setAdapter(myad);

    }

    class CustomAdapterAddContacts extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub

            System.out.println(cur.getCount());

            return cur.getCount(); // c.getCount();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            // View MyView = convertView;

            ContactViewHolder contactViewHolder;

            if (convertView == null) {

                // Inflate the layout
                LayoutInflater li = getLayoutInflater();
                convertView = li.inflate(
                        R.layout.activity_listview_addcontact_item, null);

                contactViewHolder = new ContactViewHolder();

                contactViewHolder.imgContact = (ImageView) convertView
                        .findViewById(R.id.imgView_addcontact);
                contactViewHolder.txtViewContactName = (TextView) convertView
                        .findViewById(R.id.txtView_addcontact_contactname);
                contactViewHolder.txtViewPhoneNumber = (TextView) convertView
                        .findViewById(R.id.txtview_addcontact_phonenumber);
                contactViewHolder.chbkAddContact = (CheckBox) convertView.findViewById(R.id.chbk_addcontact);

                convertView.setTag(contactViewHolder);
            } else {
                contactViewHolder = (ContactViewHolder) convertView.getTag();
            }

                cur.moveToPosition(position);



                // Add Contact Name //

                String name = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                if (name != null)
                    contactViewHolder.txtViewContactName.setText(name);
                else
                    contactViewHolder.txtViewContactName.setText("Unknown");


                // Add Phone Number //

                String phoneNumber = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                if (phoneNumber != null)
                    contactViewHolder.txtViewPhoneNumber.setText(phoneNumber);
                else
                    contactViewHolder.txtViewPhoneNumber.setText("Unknown");


                Uri uri = getPhotoUri(Long.parseLong(fetchContactIdFromPhoneNumber(phoneNumber)));


                if (uri != null) {
                    contactViewHolder.imgContact.setImageURI(uri);
                } else {
                    contactViewHolder.imgContact
                            .setImageResource(R.drawable.addcontactsmall2);
                }


            return convertView;
        }

        private String fetchContactIdFromPhoneNumber(String phoneNumber) {
            // TODO Auto-generated method stub

            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                    Uri.encode(phoneNumber));
            Cursor cFetch = getContentResolver().query(uri,
                    new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
                    null, null, null);

            String contactId = "";


            if (cFetch.moveToFirst()) {

                cFetch.moveToFirst();

                    contactId = cFetch.getString(cFetch
                            .getColumnIndex(PhoneLookup._ID));

            }

            System.out.println(contactId);

            return contactId;       

        }


        public Uri getPhotoUri(long contactId) {
            ContentResolver contentResolver = getContentResolver();

            try {
                Cursor cursor = contentResolver
                        .query(ContactsContract.Data.CONTENT_URI,
                                null,
                                ContactsContract.Data.CONTACT_ID
                                        + "="
                                        + contactId
                                        + " AND "

                                        + ContactsContract.Data.MIMETYPE
                                        + "='"
                                        + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                                        + "'", null, null);

                if (cursor != null) {
                    if (!cursor.moveToFirst()) {
                        return null; // no photo
                    }
                } else {
                    return null; // error in cursor process
                }

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            Uri person = ContentUris.withAppendedId(
                    ContactsContract.Contacts.CONTENT_URI, contactId);
            return Uri.withAppendedPath(person,
                    ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        }



        public class ContactViewHolder {
            ImageView imgContact;
            TextView txtViewContactName;
            TextView txtViewPhoneNumber;
            CheckBox chbkAddContact;
        }

    }

    private void readContacts() {
        // TODO Auto-generated method stub

        cr = getContentResolver();
        cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null, null);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        if (cur != null) {
            cur.close();
        }
    }
}

ScreenShot from my Application :::

Important Note ::: It worked for me. I may work for you as well. But, I am new to using content providers and hence may not be of much help, for queries. Experts at SO can take care of your queries.