Fetch contact photo in android gives null

2019-03-30 11:52发布

问题:

I want to fetch the photo of the contact while a user enters number.By using phone number i am getting users name but for image it shows null.

my code is following :

public class NewtempActivity extends Activity {

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

        final ImageView img = (ImageView) findViewById(R.id.imageView1);
        final EditText edit = (EditText) findViewById(R.id.editText1);
        TextView txt = (TextView) findViewById(R.id.textView1);
        Button btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Girish", "Clicked");

                String name = getContactNameFromNumber(edit.getText()
                        .toString(), getApplicationContext());
                img.setImageBitmap(BitmapFactory
                        .decodeFile(ContactsContract.PhoneLookup._ID));
                Log.d("Girish",
                        ""
                                + (BitmapFactory
                                        .decodeFile(ContactsContract.PhoneLookup._ID)));
                Toast.makeText(getApplicationContext(), name, name.length())
                        .show();
            }
        });
    }

    public String getContactNameFromNumber(String number, Context ctx) {
        /*
         * // define the columns I want the query to return String[] projection
         * = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
         * ContactsContract.PhoneLookup.NUMBER, };
         */
        // encode the phone number and build the filter URI
        Uri contactUri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(number));

        // query time
        // Cursor c = ctx.getContentResolver().query( contactUri, projection,
        // null,
        Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
                null);

        // if the query returns 1 or more results
        // return the first result
        if (c.moveToFirst()) {
            String name = c.getString(c
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));

            return name;
        }

        // return the original number if no match was found
        return number;
    }

    public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
        Uri uri = ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI, id);
        InputStream input = ContactsContract.Contacts
                .openContactPhotoInputStream(cr, uri);
        // InputStream input = ContactsContract.Contacts.Photo
        if (input == null) {
            return null;
        }
        return BitmapFactory.decodeStream(input);
    }

    public InputStream openPhoto(long contactId) {
        Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
                contactId);
        Uri photoUri = Uri.withAppendedPath(contactUri,
                Contacts.Photo.CONTENT_DIRECTORY);
        Cursor cursor = getContentResolver().query(photoUri, null, null, null,
                null);
        if (cursor == null) {
            return null;
        }
        try {
            if (cursor.moveToFirst()) {
                byte[] data = cursor.getBlob(0);
                if (data != null) {
                    return new ByteArrayInputStream(data);
                }
            }
        } finally {
            cursor.close();
        }
        return null;
    }

}

please suggest me where i am doing wrong.I have added read contact permission also

回答1:

by going through your code i came to know like You are trying to get the contact name from the number. and using that you want the contact image.. but you never called the functions which you made for the contact pic..:).. so what you can do is take id from the contact number and take photo on that id. so you will get the photo for the number..

package com.android.SampleProject;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
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.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class NewtempActivity extends Activity {

    private long id;

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

        final ImageView img = (ImageView) findViewById(R.id.imageView1);
        final EditText edit = (EditText) findViewById(R.id.editText1);
        Button btn = (Button) findViewById(R.id.button1);


        btn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Log.d("Girish", "Clicked");

                String name = getContactNameFromNumber(edit.getText()
                        .toString(), getApplicationContext());
                img.setImageBitmap(BitmapFactory
                        .decodeFile(ContactsContract.PhoneLookup._ID));
                img.setImageBitmap(loadContactPhoto(getContentResolver(), id));
                Log.d("Girish",
                        ""
                                + (BitmapFactory
                                        .decodeFile(ContactsContract.PhoneLookup._ID)));
                Toast.makeText(getApplicationContext(), name, name.length())
                        .show();
            }
        });
    }

    public String getContactNameFromNumber(String number, Context ctx) {
        /*
         * // define the columns I want the query to return String[] projection
         * = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
         * ContactsContract.PhoneLookup.NUMBER, };
         */
        // encode the phone number and build the filter URI
        Uri contactUri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(number));

        // query time
        // Cursor c = ctx.getContentResolver().query( contactUri, projection,
        // null,
        Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
                null);

        // if the query returns 1 or more results
        // return the first result
        if (c.moveToFirst()) {
            String name = c.getString(c
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
            id = c.getLong(c
                    .getColumnIndex(ContactsContract.PhoneLookup._ID));
            return name;
        }

        // return the original number if no match was found
        return number;
    }

    public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
        Uri uri = ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI, id);
        InputStream input = ContactsContract.Contacts
                .openContactPhotoInputStream(cr, uri);
        // InputStream input = ContactsContract.Contacts.Photo
        if (input == null) {
            return null;
        }
        return BitmapFactory.decodeStream(input);
    }

    public InputStream openPhoto(long contactId) {
        Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
                contactId);
        Uri photoUri = Uri.withAppendedPath(contactUri,
                Contacts.Photo.CONTENT_DIRECTORY);
        Cursor cursor = getContentResolver().query(photoUri, null, null, null,
                null);
        if (cursor == null) {
            return null;
        }
        try {
            if (cursor.moveToFirst()) {
                byte[] data = cursor.getBlob(0);
                if (data != null) {
                    return new ByteArrayInputStream(data);
                }
            }
        } finally {
            cursor.close();
        }
        return null;
    }

}