DEV Community

loading...
Cover image for Questioning old habbits

Questioning old habbits

tkuenneth profile image Thomas Kuenneth ・2 min read

In this short piece I cover a topic that may sound, well, boring. It's about reading contatcs on Android. But I am not interested in permissions or how to retrieve them most efficently. It's more like getting them at all. Through the years I advocated a rather simple algorithm:

val mainQueryProjection = arrayOf(Contacts._ID)
val mainQuerySelection = """
  ${Contacts.IN_VISIBLE_GROUP} = ? AND 
  ${Contacts.DISPLAY_NAME} IS ?
""".cleanup()
val mainQuerySelectionArgs = arrayOf("1", "a name")
contentResolver.query(
  Contacts.CONTENT_URI,
  mainQueryProjection,
  mainQuerySelection, mainQuerySelectionArgs, null
)?.run {
  if (moveToNext()) {
    val contactId = getString(0)
    println("===> found ($contactId)")
  } else {
    println("a name not found")
  }
  close()
}
Enter fullscreen mode Exit fullscreen mode

To find a contact this way, two conditions must be met:

  • Contacts.DISPLAY_NAME must be a name
  • Contacts.IN_VISIBLE_GROUP must be 1

According to the docs, Contacts.IN_VISIBLE_GROUP is an

indicator of whether this contact is supposed to be visible
in the UI. "1" if the contact has at least one raw contact that
belongs to a visible group; "0" otherwise.

This has been working well through the years and it actually is still working these days. Unless I run that code on my Lenovo Duet. For whatever reason my contacts seem to not be in a visible group. Certainly, in both cases the same Google account had been used.

Now, the check for being visible seemed a good idea, because there had always been contacts that consisted only of an email address. Especially in the early days (when performance was a concern) it was a good idea to filter out unneeded results before the app processed the remaining ones. Today performance is no longer an issue. Still, shouldn't we try to make our apps as efficient as we can?

Certainly.

There's a Google doc called Retrieve a list of contacts.

It shows a pragmatic resolutuion:

Screenshot showing a portion of a webpage

So the idea is: If there's a name let's process the contact. Depending on what your app wants to do you can add additional criteria.

As I have no idea what causes the different behavior I will change my app accordingly. Have you encountered this, too? How did you solve it? Please share your thoughts in the comments.

Discussion (0)

pic
Editor guide