-1

I implemented a code to retrieve all contacts but it is not showing all contacts where few of them are missed. Here is my code:

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

don't know what is happening. Please help me.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
basha
  • 587
  • 2
  • 6
  • 25

1 Answers1

1

There are many issues in the code:

  1. You're querying over the CommonDataKinds.Phone.CONTENT_URI table, so naturally, you won't get contacts that have no phone numbers (e.g. contacts with name and email)
  2. You're skipping contacts that contains phones you've already encountered in normalizedNumbersAlreadyFound, so if you have two contacts with a shared phone (like a home phone number) you might skip one of them.
  3. CommonDataKinds.Phone.NORMALIZED_NUMBER may be null, in which case you'll skip many contacts that do not have their NORMALIZED_NUMBER field set

If you need to also include contacts that have no phones, I would recommend a completely different code. If you only need to get contacts with phones, I would recommend not relying on NORMALIZED_NUMBER, and instead add CommonDataKinds.Phone.CONTACT_ID to your projection, and have that as your unique key per contact.

marmor
  • 27,641
  • 11
  • 107
  • 150