【问题标题】:Getting Photos of contacts获取联系人照片
【发布时间】:2014-01-14 21:49:21
【问题描述】:

我正在努力通过光标获取联系人。一切正常,但显示联系人照片并没有返回任何内容。我没有遇到任何崩溃或错误。我的代码是

ContactListActivity.java

Cursor cur= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,null);
        list.setAdapter(new contactAdapter(getApplicationContext(), cur));

我自定义创建的光标适配器是

class contactAdapter extends CursorAdapter{

        String Name, phoneNumber;
        private Cursor cursor;
        private Context ccontext;
        private LayoutInflater inflater;

        public contactAdapter(Context context, Cursor c) {
            super(context, c);
            // TODO Auto-generated constructor stub
            cursor = c;
            ccontext = context;
            inflater = LayoutInflater.from(context);
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @SuppressLint("InlinedApi")
        @SuppressWarnings("deprecation")
        @Override
        public void bindView(View view, Context arg1, Cursor arg2) {
            // TODO Auto-generated method stub

            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.contactsImage = (ImageView) view.findViewById(R.id.contact_image);
                holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
                holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
                view.setTag(holder);
                holder.contactCheck.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        cb = (CheckBox) v;
                        cb.setChecked(cb.isChecked());
//                      ContactPerson selected = (ContactPerson)cb.getTag();
                        Log.d("selcted", cb.getTag().toString());
                        if(cb.isChecked()){

                            phoneID.add(cb.getTag().toString());


                        }
                    }

                }); 
            }else{
                holder = (ViewHolder) view.getTag();
            }
//          Uri uri = ContentUris.withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));
//          Log.d("ImagePath", ContactsContract.CommonDataKinds.Phone.PHOTO_FILE_ID);
            if(cursor.getString(cursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
               byte[] photoByte = cursor.getBlob(cursor.getColumnIndex("data15"));

                if(photoByte != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);

                    // Getting Caching directory
                    File cacheDirectory = getBaseContext().getCacheDir();

                    // Temporary file to store the contact image
                    File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID))+".png");

                    // The FileOutputStream to the temporary file
                    try {
                        FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                        // Writing the bitmap to the temporary file as png file
                        bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

                        // Flush the FileOutputStream
                        fOutStream.flush();

                        //Close the FileOutputStream
                        fOutStream.close();
                        holder.contactsImage.setImageBitmap(bitmap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                   String photoPath = tmpFile.getPath();
                   Log.d("photoPath", photoPath);
                }
            }
//          holder.contactsImage.setImageBitmap(bitmap);
            holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
            holder.contactCheck.setTag(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
            holder.contactCheck.setChecked(false);

        }

        @Override
        public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            return inflater.inflate(R.layout.checkbox_item, arg2, false);
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
//          Log.d("don't know", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
            return super.getView(arg0, arg1, arg2);
        }

    }

谁能告诉我哪里出错并指导我获取照片。我到处搜索并实现了代码。但它们都没有产生所需的结果。

【问题讨论】:

    标签: android android-contentprovider android-contacts android-cursoradapter


    【解决方案1】:

    这是您可以从联系人 URI 获取图像的代码。

    String image_uri    = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));   
    bitmap = MediaStore.Images.Media .getBitmap(this.getContentResolver(), Uri.parse(image_uri)); 
    contactpic.setImageBitmap(bitmap) ;
    

    【讨论】:

    • 它显示为“12-27 15:39:26.387: E/CursorWindow(21442): Bad request for field slot 0,-1. numRows = 100, numColumns = 63”
    【解决方案2】:

    试试这个代码

    private void getContactsDetails() {
    
            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 Number = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    
                String image_uri = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
    
                System.out.println("Contact1 : " + Name + ", Number " + Number
                        + ", image_uri " + image_uri);
    
    
                if (image_uri != null) {
                     image.setImageURI(Uri.parse(image_uri));
                    }
    
    
            }
    

    【讨论】:

      【解决方案3】:

      尝试以下方法获取联系人姓名和联系人照片。

      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.imageView1);
                      imageView.setImageBitmap(photo);
                  }
      
                  assert inputStream != null;
                  inputStream.close();
      
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
          }
      
          /**
           * super fast query to pull email addresses. It is much faster than pulling
           * all contact columns as suggested by other answers...
           * 
           * @return
           */
          public ArrayList<ContactVo> getNameEmailDetails() {
              ArrayList<ContactVo> m_arrList = new ArrayList<ContactVo>();
              ArrayList<String> emlRecs = new ArrayList<String>();
              HashSet<String> emlRecsHS = new HashSet<String>();
              ContentResolver cr = m_context.getContentResolver();
              String[] PROJECTION = new String[] { ContactsContract.RawContacts._ID,
                      ContactsContract.Contacts.DISPLAY_NAME,
                      ContactsContract.Contacts.PHOTO_ID,
                      ContactsContract.CommonDataKinds.Email.DATA,
                      ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
              String order = "CASE WHEN " + ContactsContract.Contacts.DISPLAY_NAME
                      + " NOT LIKE '%@%' THEN 1 ELSE 2 END, "
                      + ContactsContract.Contacts.DISPLAY_NAME + ", "
                      + ContactsContract.CommonDataKinds.Email.DATA
                      + " COLLATE NOCASE";
              String filter = ContactsContract.CommonDataKinds.Email.DATA
                      + " NOT LIKE ''";
              Cursor cur = cr.query(
                      ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION,
                      filter, null, order);
              ContactVo m_vo;
              if (cur.moveToFirst()) {
                  do {
                      m_vo = new ContactVo();
                      // names comes in hand sometimes
                      String name = cur.getString(1);
                      String emlAddr = cur.getString(3);
                      System.err.println("Value Is---------->" + cur.getString(2)
                              + "Name--" + name + "Email---" + emlAddr);
                      m_vo.setM_sName(name);
                      m_vo.setM_sEmail(emlAddr);
                      // keep unique only
                      if (emlRecsHS.add(emlAddr.toLowerCase())) {
                          emlRecs.add(emlAddr);
                      }
                      m_arrList.add(m_vo);
                  } while (cur.moveToNext());
              }
      
              cur.close();
              return m_arrList;
          }
      

      【讨论】:

        猜你喜欢
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 2012-08-27
        • 2011-11-12
        • 1970-01-01
        • 1970-01-01
        • 2011-09-23
        相关资源
        最近更新 更多