【问题标题】:All Contacts are not showing while retrieving contacts检索联系人时未显示所有联系人
【发布时间】:2017-12-30 06:32:11
【问题描述】:

我实现了一个代码来检索所有联系人,但它没有显示所有联系人,其中很少有人遗漏。 这是我的代码:

 String[] projection = new String[]{
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
        };
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    projection, null, null, null);
        } catch (SecurityException e) {
        }
        if (cursor != null) {
            try {
                HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
                int indexOfNormalizedNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER);
                int indexOfDisplayName = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                int indexOfDisplayNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                while (cursor.moveToNext()) {
                    String normalizedNumber = cursor.getString(indexOfNormalizedNumber);
                    if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
                        String displayName = cursor.getString(indexOfDisplayName);
                        String displayNumber = cursor.getString(indexOfDisplayNumber);

                        listOfContacts.add(new PhoneContactsModel(displayName, displayNumber, false));

                    } else {
                    }
                }
                Log.d("tag", "size of listOfContacts =1====" + listOfContacts.size());


            } finally {
                cursor.close();
            }
        }

不知道发生了什么。请帮帮我。

【问题讨论】:

    标签: android android-contacts android-contentresolver


    【解决方案1】:

    代码中有很多问题:

    1. 您正在查询 CommonDataKinds.Phone.CONTENT_URI 表,因此很自然地,您不会得到没有电话号码的联系人(例如,有姓名和电子邮件的联系人)
    2. 您正在跳过包含您已经在normalizedNumbersAlreadyFound 中遇到过的电话的联系人,因此如果您有两个使用共享电话的联系人(例如家庭电话号码),您可能会跳过其中一个。
    3. CommonDataKinds.Phone.NORMALIZED_NUMBERmay be null,在这种情况下,您将跳过许多没有设置NORMALIZED_NUMBER 字段的联系人

    如果您还需要包含没有电话的联系人,我建议您使用完全不同的代码。如果您只需要通过手机获取联系人,我建议您不要依赖NORMALIZED_NUMBER,而是将CommonDataKinds.Phone.CONTACT_ID 添加到您的投影中,并将其作为每个联系人的唯一密钥。

    【讨论】:

      猜你喜欢
      • 2016-04-08
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 2011-12-27
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多