Android get contacts getting really long when multiple Google accounts are connected to phone

62 views Asked by At

maybe somone knows solution how to get phone contacts only from main google account, not all of them, otherwise it takes ages to load. Here is the code that I am using:

  private val projectionForPhoneNumber by lazy {
        arrayOf(
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone._ID,
            ContactsContract.CommonDataKinds.Phone.PHOTO_URI,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.TYPE,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
        )
    }
    private val projectionForNames by lazy {
        arrayOf(
            ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
            ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME
        )
    }
    private val phoneNoPattern = "[()\\s-]+".toRegex()

  context.contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projectionForPhoneNumber, null, null, null
            )?.use { phoneCursor ->
                phoneCursor.apply {
                    while (moveToNext()) {
                        try {
                            val contactId = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID))
                            val nameQuery = "${ContactsContract.Data.MIMETYPE} = ? " +
                                "AND ${ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID} = $contactId"

                            val nameQueryParams =
                                arrayOf(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)

                            context.contentResolver.query(
                                ContactsContract.Data.CONTENT_URI,
                                projectionForNames,
                                nameQuery,
                                nameQueryParams,
                                null
                            )?.use { nameCursor ->
                                mapPhoneContact(contacts, nameCursor)
                            }
                        } catch (exception: Exception) {
                            exceptionsLogger.logError(exception)
                        }
                    }
                }
            }

            val collator = Collator.getInstance(Locale.getDefault())
            contacts.values
                .sortedWith { first, second -> collator.compare(first.name, second.name) }
                .sortedBy { first -> first.name.firstOrNull()?.isLetter() == false }
0

There are 0 answers