Android - 检索联系人照片和显示

Posted

技术标签:

【中文标题】Android - 检索联系人照片和显示【英文标题】:Android - Retrieve Contact Photo and Display 【发布时间】:2013-09-16 16:59:57 【问题描述】:

我正在创建一个简单的应用程序,该应用程序检索每个联系人的姓名和电话号码,并在列表视图中与联系人的照片一起显示在行首的缩略图大小的图像视图中。

我已设法检索并显示姓名和号码,但在浏览了许多教程和堆栈后未能显示照片。

我最终回滚到只显示姓名和号码。

任何人都可以帮助提供联系人照片,我在下面提供了我的代码。

提前致谢!

---接触getter和setter--- 此方法正确获取名称和编号,但我不确定我是否正确获取照片。

 package content;

 import android.net.Uri;


 public class ContactBean 
private String name;
private String phoneNo;
private Uri proPic;

public String getName() 
    return name;

public void setName(String name) 
    this.name = name;

public String getPhoneNo() 
    return phoneNo;

public void setPhoneNo(String phoneNo) 
    this.phoneNo = phoneNo;


public Uri getPhotoUri() 
    return this.proPic;


public void setPhotoUri(Uri photoUri) 
    this.proPic = proPic;



---BackUpListActivity---

package backUpContacts;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import backUpContacts.BackUpListActivity;

import com.example.contactflipper.R;

import content.ContactBean;


 import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
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.view.View;
import android.widget.AdapterView;
 import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BackUpListActivity extends Activity implements
OnItemClickListener 

private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
private String contactID;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.save_backups);

    listView = (ListView) findViewById(R.id.list);
    listView.setOnItemClickListener(this);
    String image_uri = "";
    Bitmap bitmap = null;

    Cursor phones = getContentResolver().query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,  null,
            null, null);
    while (phones.moveToNext()) 

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

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


        ContactBean objContact = new ContactBean();
        objContact.setName(name);
        objContact.setPhoneNo(phoneNumber);
        list.add(objContact);

    
    phones.close();

    BackUpListAdapter objAdapter = new BackUpListAdapter(
            BackUpListActivity.this, R.layout.save_list_row, list);
    listView.setAdapter(objAdapter);

    if (null != list && list.size() != 0) 
        Collections.sort(list, new Comparator<ContactBean>() 

            @Override
            public int compare(ContactBean lhs, ContactBean rhs) 
                return lhs.getName().compareTo(rhs.getName());
            
        );
        AlertDialog alert = new AlertDialog.Builder(
                BackUpListActivity.this).create();
        alert.setTitle("");

        alert.setMessage(list.size() + " Contact Found!!!");

        alert.setButton("OK", new DialogInterface.OnClickListener() 

            @Override
            public void onClick(DialogInterface dialog, int which) 
                dialog.dismiss();
            
        );
        alert.show();

     else 
        showToast("No Contact Found!!!");
    


private void showToast(String msg) 
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();



@Override
public void onItemClick(AdapterView<?> listview, View v, int position,
        long id) 
    ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
    //implement something on the click of each listed item - bean



---BackUpListAdapter---

package backUpContacts;

import java.util.ArrayList;
import java.util.List;

import viewContacts.GridAdapter.ViewHolder;

import com.example.contactflipper.R;

 import content.ContactBean;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
 import android.text.html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

public class BackUpListAdapter extends ArrayAdapter<ContactBean> implements  OnClickListener

private Activity activity;
private List<ContactBean> items;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
private int row;
private ContactBean objBean;

public BackUpListAdapter(Activity act, int row, List<ContactBean> items) 
    super(act, row, items);

    this.activity = act;
    this.row = row;
    this.items = items;

    for (int i = 0; i < this.getCount(); i++) 
        itemChecked.add(i, false); // initializes all items value with false
    



@Override
public View getView(final int position, View convertView, ViewGroup parent) 
    View view = convertView;
    ViewHolder holder;
    if (view == null) 
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(row, null);

        holder = new ViewHolder();
        view.setTag(holder);


     else 
        holder = (ViewHolder) view.getTag();
    

    if ((items == null) || ((position + 1) > items.size()))
        return view;

    objBean = items.get(position);

    holder.tvname = (TextView) view.findViewById(R.id.tvname);
    holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
    holder.ivPic = (ImageView) view.findViewById(R.id.profile_pic);

    if (holder.tvname != null && null != objBean.getName()
            && objBean.getName().trim().length() > 0) 
        holder.tvname.setText(Html.fromHtml(objBean.getName()));
    
    if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
            && objBean.getPhoneNo().trim().length() > 0) 
        holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
    


    final CheckBox cBox = (CheckBox) view.findViewById(R.id.chkMarkContact); // your
    // CheckBox
    cBox.setOnClickListener(new OnClickListener() 

        public void onClick(View v) 

            CheckBox cb = (CheckBox) v.findViewById(R.id.chkMarkContact);

            if (cb.isChecked()) 
                itemChecked.set(position, true);
                // do some operations here
             else if (!cb.isChecked()) 
                itemChecked.set(position, false);
                // do some operations here
            
        
    );
    cBox.setChecked(itemChecked.get(position)); // this will Check or Uncheck the
    // CheckBox in ListView
    // according to their original
    // position and CheckBox never
    // loss his State when you
    // Scroll the List Items.



    return view;


public class ViewHolder 
    public TextView tvname, tvPhoneNo;
    public ImageView ivPic;


@Override
public void onClick(View arg0) 
    // TODO Auto-generated method stub




在上面的代码中,我相信我需要类似的东西

if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
            && objBean.getPhoneNo().trim().length() > 0) 
        holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
    

除了要显示的照片。

我也已经在xml中创建了一个imageview,并在上面的代码中声明了

  holder.ivPic = (ImageView) view.findViewById(R.id.profile_pic);

【问题讨论】:

看看答案。 我目前正在尝试实现它,我被 _ID 弄糊涂了它给了我错误,不太确定它的实际用途。谢谢 它的包'android.provider.ContactsContract.Contacts' 我应该在适配器中这样做吗?抱歉,我对 android 很陌生 这样做:将'contact_id'保存在ContactBean类中,并在适配器类的getview()中实现图像检索。 【参考方案1】:

您尝试获取联系人的联系人 ID(电话号码)并使用 Bitmapfactory 解码图像,如下面的工作代码所示。

InputStream inputStream=null;
String[] projection = new String[]Contacts._ID;
Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,Uri.encode(phnumber));
Cursor c = getContentResolver().query(contactUri, projection,
    null, null, null);
if (c.moveToFirst()) 
    long contactId=c.getColumnIndex(Contacts._ID);

    inputStream = Contacts.openContactPhotoInputStream(activity.getContentResolver(),
                            ContentUris.withAppendedId(Contacts.CONTENT_URI, cntID));
    c.close();


使用输入流获取位图

Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
 holder.ivPic.setImageBitmap(bitmap);

【讨论】:

?代码几天前工作了,现在它不工作了?......现在接受一次又一次拒绝答案的原因是什么。 此解决方案有效,谢谢。我唯一需要改变的是 long contactId=c.getColumnIndex(Contacts._ID) 到 long contactId = c.getLong(c.getColumnIndex(Contacts._ID))

以上是关于Android - 检索联系人照片和显示的主要内容,如果未能解决你的问题,请参考以下文章

在 Android 上检索联系人图像

将联系人的照片写入vcf文件,android

如何使用 Android 将手机联系人照片的总列表上传到服务器?

Android 2.3 和 Android 4.0 上的联系人照片 uri

从android中的电话簿中检索whatsapp联系人

android 上的外部(例如 facebook)联系人照片