【问题标题】:Retrieve Contacts faster from address book in android从android中的通讯录中更快地检索联系人
【发布时间】:2014-10-03 04:10:34
【问题描述】:

我想检索所有联系人的详细信息,例如“电话号码”、“显示名称”、“显示图像”和“电子邮件 ID”。我正在使用下面的方法来做到这一点,它工作正常。

public void readContacts() {
    Log.d("readcontacts", "::" + "true");
    String phoneNumber = null;
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            // contactEntity = new ContactEntity();
            final ContentValues values = new ContentValues();
            String Contact_Id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));
            values.put(KEY_ID, Integer.parseInt(Contact_Id));

            int hasPhoneNumber = Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            /*
             * contactEntity .setContactFirstName(cur.getString(cur
             * .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
             */

            if (Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                // System.out.println("name : " + name + ", ID : " + id);
                // sb.append("\n Contact Name:" + name);
                Cursor pCur = cr
                        .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = ?",
                                new String[] { Contact_Id }, null);
                if (pCur.moveToFirst()) {
                    phoneNumber = pCur
                            .getString(pCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    // sb.append("\n Phone number:" + phone);
                    // System.out.println("phone" + phone);

                }
                pCur.close();

                Cursor emailCur = cr
                        .query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                        + " = ?",
                                new String[] { Contact_Id }, null);
                if (emailCur.moveToFirst()) {
                    values.put(
                            KEY_CONTACTEMAIL,
                            (emailCur.getString(emailCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))));
                    // emailType = emailCur .getString(emailCur
                    // .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

                }
                emailCur.close();

                if (phoneNumber.length() >= 10) {
                    final Uri my_contact_Uri = Uri.withAppendedPath(
                            ContactsContract.Contacts.CONTENT_URI,
                            String.valueOf(Contact_Id));


                                InputStream photo_stream = ContactsContract.Contacts
                                        .openContactPhotoInputStream(
                                                getContentResolver(),
                                                my_contact_Uri);
                                if (photo_stream != null) {
                                    BufferedInputStream buf = new BufferedInputStream(
                                            photo_stream);
                                    Bitmap my_btmp = BitmapFactory
                                            .decodeStream(buf);
                                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                    my_btmp.compress(Bitmap.CompressFormat.PNG,
                                            100, bos);
                                    byte[] bArray = bos.toByteArray();
                                    values.put(KEY_CONTACTIMAGE, bArray);
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }


                    // contactEntity.setBitmapContactImage(my_btmp);
                    values.put(
                            KEY_CONTACTNAME,
                            String.valueOf(cur.getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))));
                    values.put(KEY_CONTACTNUMBER,
                            String.valueOf(phoneNumber));
                    databaseHelperAssets.open();
                    databaseHelperAssets.addcontact(values);
                    databaseHelperAssets.close();
                }

            }
            // values.put(KEY_TIMESWAP,
            // String.valueOf(taskEnitiy.getTimeswap()));
            // int SDK_INT = android.os.Build.VERSION.SDK_INT;

            /*
             * if (SDK_INT >= 11) { contactEntity
             * .setImgUri(cur.getString(cur
             * .getColumnIndex(ContactsContract.
             * CommonDataKinds.Phone.PHOTO_URI))); }
             */
            // alContactEntities.add(contactEntity);
        }
    }

}

但问题是检索大约 400 个联系人的详细信息大约需要 45 秒到 1 分钟。每次需要检索联系人时,我都不能让我的用户等待这么长时间。那么任何人都可以帮助我减少联系的检索时间吗?是的,我用来将我的联系人存储在数据库中,因为我只有在应用程序启动时才第一次读取我的联系人。所以我会找到更好的方法来检索它,我可以排除在数据库中存储联系人。提前致谢!!

【问题讨论】:

  • 是否需要在每次写入时打开和关闭databaseHelperAssets
  • 其实我不想使用数据库我想动态显示它
  • 我在循环外更改了数据库打开和关闭的操作,但对我来说仍然需要很长时间
  • 好吧,如果你想消除数据库,那么完全摆脱数据库操作,并将联系人信息直接读入列表。
  • 我认为使用ContentProviderOperation进行批量操作会有所帮助。

标签: android contacts addressbook


【解决方案1】:

感谢大家的帮助和提示,但最终我得到了答案。我正在使用下面的代码来获取显示图像:

  InputStream photo_stream = ContactsContract.Contacts
                                    .openContactPhotoInputStream(
                                            getContentResolver(),
                                            my_contact_Uri);
                            if (photo_stream != null) {
                                BufferedInputStream buf = new BufferedInputStream(
                                        photo_stream);
                                Bitmap my_btmp = BitmapFactory
                                        .decodeStream(buf);
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                my_btmp.compress(Bitmap.CompressFormat.PNG,
                                        100, bos);
                                byte[] bArray = bos.toByteArray();
                                values.put(KEY_CONTACTIMAGE, bArray);
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

但是我把它改成:

try {
                String phototjumb = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
                if(phototjumb != null && !phototjumb.toString().equalsIgnoreCase("")){
                    contactEntity.setImageURI(phototjumb);
                    Log.d("photojumb", "::" + phototjumb);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

并且比我用来在我的 Imageview 上显示该 photojumb 为:

 imgContactImg.setImageURI(Uri.parse(contactEntity.getImageURI()));

就是这样。现在,我几乎不需要 2 秒就可以直接在自定义列表视图中即时显示联系人。

别担心,我正在发布我的完整方法来检索联系人。这里是::

@SuppressLint("InlinedApi")
public void readContacts() {
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            contactEntity = new ContactEntity();
            String Contact_Id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));
            contactEntity
                    .setContactFirstName(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));


            try {
                String phototjumb = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
                if(phototjumb != null && !phototjumb.toString().equalsIgnoreCase("")){
                    contactEntity.setImageURI(phototjumb);
                    Log.d("photojumb", "::" + phototjumb);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            alContactEntities.add(contactEntity);
        }
    }

}

祝您编码愉快。 :)

请通过下面附加的更新代码获取联系号码、显示名称、显示图像、电子邮件 ID 等。

public ArrayList<ContactEntity> readContacts1() {
    //Log.d("readcontacts", "::" + "true");
    alContactEntities = new ArrayList<ContactEntity>();
    String phoneNumber = null;
    String tempPhoneNumber = null;
    contactCount = 0;
    ContentResolver cr = activity.getContentResolver();

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

    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            contactEntity = new ContactEntity();

            String Contact_Id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));

            if (Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER))) > 0) {
                /*
                 * // System.out.println("name : " + name + ", ID : " + id);
                 * // sb.append("\n Contact Name:" + name);
                 */
                /*
                 * Cursor pCur = cr
                 * .query(ContactsContract.CommonDataKinds.Phone
                 * .CONTENT_URI, null,
                 * ContactsContract.CommonDataKinds.Phone.CONTACT_ID +
                 * " = ?", new String[] { Contact_Id }, null); if
                 * (pCur.moveToFirst()) {
                 */
                phoneNumber = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));



                /*
                 * String regexStr = "^[0-9\\-\\+]*$"; phoneNumber =
                 * phoneNumber.replaceAll("\\D","");
                 */
                //Log.d("PohneNumber", "" + phoneNumber);

                /*
                 * } pCur.close();
                 */

                // remove comment from below code to obtain email id
                /*Cursor emailCur = cr
                        .query(ContactsContract.CommonDataKinds
                                        .Email.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Email.CONTACT_ID +
                                        " = ?", new String[]{Contact_Id}, null);
                if
                        (emailCur.moveToFirst()) {
                    contactEntity.setContactEmailId
                            ((emailCur.getString(emailCur
                                    .getColumnIndex(ContactsContract
                                            .CommonDataKinds.Email.DATA))));
                }
                emailCur.close();*/

                Uri uriBirthdate = ContactsContract.Data.CONTENT_URI;

                String[] projectionBirthdate = new String[]{
                        ContactsContract.Contacts.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Event.CONTACT_ID,
                        ContactsContract.CommonDataKinds.Event.START_DATE
                };

                String whereBirthdateCaluse =
                        ContactsContract.CommonDataKinds.Event.CONTACT_ID + "= ? AND " +
                                ContactsContract.Data.MIMETYPE + "= ? AND " +
                                ContactsContract.CommonDataKinds.Event.TYPE + "=" +
                                ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
                String[] selectionArgsBirthdate = new String[]{Contact_Id,
                        ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
                };
                String sortOrder = null;
                Cursor birthDayCur = cr.query(uriBirthdate, projectionBirthdate, whereBirthdateCaluse,
                        selectionArgsBirthdate, sortOrder);

                if
                        (birthDayCur.moveToFirst()) {
                    int bDayColumn = birthDayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
                    String bDay = birthDayCur.getString(bDayColumn);
                    Log.d("Birthday", " : " + bDay);
                }
                birthDayCur.close();


                if (phoneNumber.length() >= 9
                        && UDF.isValidPhoneNumber(phoneNumber)) {
                    /*
                     * Uri my_contact_Uri = Uri.withAppendedPath(
                     * ContactsContract.Contacts.CONTENT_URI,
                     * String.valueOf(Contact_Id));
                     * 
                     * try { final InputStream photo_stream =
                     * ContactsContract.Contacts
                     * .openContactPhotoInputStream( activity.getContentResolver(),
                     * my_contact_Uri); if (photo_stream != null) { new
                     * Thread(new Runnable() {
                     * 
                     * @Override public void run() { BufferedInputStream buf
                     * = new BufferedInputStream( photo_stream); Bitmap
                     * my_btmp = BitmapFactory .decodeStream(buf);
                     * ByteArrayOutputStream bos = new
                     * ByteArrayOutputStream();
                     * my_btmp.compress(Bitmap.CompressFormat.PNG, 100,
                     * bos); byte[] bArray = bos.toByteArray();
                     * values.put(KEY_CONTACTIMAGE, bArray);
                     * 
                     * } }).start();
                     * 
                     * 
                     * } } catch (Exception e) { // TODO Auto-generated
                     * catch block e.printStackTrace(); } //
                     * contactEntity.setBitmapContactImage(my_btmp);
                     */
                    try {
                        String phototjumb = null;
                        int SDK_INT = android.os.Build.VERSION.SDK_INT;
                        if (SDK_INT >= 11) {
                            phototjumb = cur
                                    .getString(cur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                        } else {
                            phototjumb = cur
                                    .getString(cur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                        }

                        if (phototjumb != null
                                && !phototjumb.toString().equalsIgnoreCase(
                                "")) {
                            contactEntity.setImageURI(phototjumb);
                            //Log.d("photojumb", "::" + phototjumb);
                        }


                        /*if(eventEntity.getContactIndex() != -1 && contactCount == eventEntity.getContactIndex()){
                            if(eventEntity.getBlobImage() != null){
                                byte[] bb = eventEntity.getBlobImage();

                                String selectedImagePath = getRealPathFromURI(getImageUri(
                                        activity,
                                        BitmapFactory.decodeByteArray(bb, 0, bb.length)));

                                Bitmap vt = BitmapFactory.decodeFile(selectedImagePath);

                                Bitmap bitmap = Bitmap
                                        .createScaledBitmap(vt, 50, 50, false);

                                //imgContactImg.setImageBitmap(UDF.getCroppedBitmap(bitmap));

                                contactEntity.setImageURI(
                                        getImageUri(activity, vt).toString());
                            }


                        }*/

                        /*
                         * InputStream photo_stream =
                         * ContactsContract.Contacts
                         * .openContactPhotoInputStream
                         * (activity.getContentResolver(), my_contact_Uri);
                         * if(photo_stream != null){ // Use this method to
                         * set image using input stream
                         * 
                         * contactEntity.setInputStreamImage(photo_stream);
                         * 
                         * //Use this method to set image using bitmap (But
                         * it is time consuming)
                         * 
                         * BufferedInputStream buf = new
                         * BufferedInputStream(photo_stream); Bitmap my_btmp
                         * = BitmapFactory.decodeStream(buf);
                         * contactEntity.setBitmapContactImage(my_btmp); }
                         */
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (cur.getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)) == null
                            || cur.getString(
                            cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                            .trim().equalsIgnoreCase("")) {
                        contactEntity.setContactFirstName(String
                                .valueOf(phoneNumber));
                    } else {
                        contactEntity
                                .setContactFirstName(String.valueOf(cur.getString(cur
                                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))));
                    }

                    contactEntity.setContactNumber(String
                            .valueOf(phoneNumber));
                    contactEntity.setUniquePosition(contactCount);
                    contactCount++;

                    alContactEntities.add(contactEntity);

                }

            }
            // values.put(KEY_TIMESWAP,
            // String.valueOf(taskEnitiy.getTimeswap()));
            // int SDK_INT = android.os.Build.VERSION.SDK_INT;

            /*
             * if (SDK_INT >= 11) { contactEntity
             * .setImgUri(cur.getString(cur
             * .getColumnIndex(ContactsContract.
             * CommonDataKinds.Phone.PHOTO_URI))); }
             */
            // alContactEntities.add(contactEntity);

        }
    }
    cur.close();
    return alContactEntities;
}

对于 UDF.isValidPhoneNumber(phoneNumber)

/**
 * Check if phone number is valid or not
 */
public static final boolean isValidPhoneNumber(CharSequence target) {
    if (target == null || TextUtils.isEmpty(target)) {
        return false;
    } else {
        return android.util.Patterns.PHONE.matcher(target).matches();
    }
}

【讨论】:

  • 你没有发布完整代码我的意思是阅读电话号码和电子邮件 ID
  • 我在 2200 联系人中面临同样的问题,但将数据加载到列表中需要很长时间。能否请您发布完整的代码。
  • @Ajit- 这是从通讯录中读取所有联系人的完整代码。如果有 2200 个联系人,则不会超过 3 到 4 秒。您可以在“alContactEntities”中获取所有联系人的数组
  • 它会提供电话号码和电子邮件 ID?
  • @Jigar- 我认为您只阅读姓名和个人资料 uri,我需要电话号码和电子邮件 ID
猜你喜欢
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 2023-03-12
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多