Получение фотографий контактов

Я работаю над получением контактов через курсор. Все работает нормально, но отображение фотографий контактов ничего не возвращает. Я не получаю никаких сбоев или ошибок. Мой код

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

    }

Может кто-нибудь, пожалуйста, скажите мне, где я иду не так, и направьте меня, чтобы получить фотографии. Я гуглю везде и внедряю код. Но ни один из них не дал требуемого результата.

3 ответа

Попробуй этот код

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


        }

Вот код, который вы можете получить изображение из контактного 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) ;

Попробуйте описанный ниже метод, чтобы получить имя контакта и фотографию контакта.

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;
    }
Другие вопросы по тегам