检索联系人列表的最佳方法

时间:2017-11-23 07:23:54

标签: android android-contacts

我正在开发一个有三个片段的联系人应用程序(callLog,contactList,favoriteContactList)。当将一个片段移动到另一个片段时,需要时间来检索所有联系人。我的设备上有大约276个联系人。任何可以减少时间的解决方案。

ContentResolver cr = getContext().getContentResolver();
        String[] projection = {ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.PHOTO_URI,
                ContactsContract.Contacts.HAS_PHONE_NUMBER};

        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        String id, name, image_uri, phone = "";

        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {

                id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                image_uri = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));

                Log.d(TAG, " name " + name + " id " + id);

                // phone number
                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    if (pCur != null && pCur.moveToNext()) {

                        phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        int colIndex = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                        int lblIndex = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL);
                        int labelType = pCur.getInt(colIndex);
                        String phoneType;

                        if (labelType == ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM) {
                            phoneType = pCur.getString(colIndex);
                        } else {
                            phoneType = String.valueOf(ContactsContract.CommonDataKinds.Phone.getTypeLabel(this.getResources(), labelType, "Mobile"));
                        }

                        Log.d(TAG, phoneType + " " + phone);
                        pCur.close();
                    }
                    mContactArrayList.add(new Contact(id, name, phone, image_uri));
                }
            }
            cur.close();
        }

1 个答案:

答案 0 :(得分:2)

试试这个代码

{{1}}

我认为它有效。