草庐IT

java - Android : Duplicate contact data while retrieving contacts using ContactsContract. CommonDataKinds.Phone

coder 2023-12-07 原文

我浏览了很多帖子,但没有找到任何有效甚至正确回答问题的答案。我最接近的是这个 How to avoid duplicate contact name (data ) while loading contact info to listview?但这有太多的开销。有没有更简单或更有效的方法来解决这个问题?

最佳答案

我遇到了与您相同的问题:我收到了重复的电话号码。我通过获取每个游标条目的标准化数字 并使用HashSet 来跟踪我已经找到的数字来解决这个问题。试试这个:

private void doSomethingForEachUniquePhoneNumber(Context context) {
    String[] projection = new String[] {
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
            //plus any other properties you wish to query
    };

    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
    } catch (SecurityException e) {
        //SecurityException can be thrown if we don't have the right permissions
    }

    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);
                    //haven't seen this number yet: do something with this contact!
                } else {
                    //don't do anything with this contact because we've already found this number
                }
            }
        } finally {
            cursor.close();
        }
    }
}

关于java - Android : Duplicate contact data while retrieving contacts using ContactsContract. CommonDataKinds.Phone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39185338/

有关java - Android : Duplicate contact data while retrieving contacts using ContactsContract. CommonDataKinds.Phone的更多相关文章

随机推荐