DEV Community

Cover image for I wrote an API in Kotlin +Flow to make Android Contacts straightforward to use (no ContentProviders)
Alex Styl
Alex Styl

Posted on

I wrote an API in Kotlin +Flow to make Android Contacts straightforward to use (no ContentProviders)

Historically, using the Contacts API in Android has been a pain. Developers need to use ContentProviders which can be tedious to work with. The lack of a type-safe API leads to repeated errors, developer frustration, along with a waste of time and resources for the developer and the team.

As a result, ContactStore was born. Contact Store is a modern contacts Android API written in Kotlin. It utilises Coroutine's Flow to notify the developer for updates happening to the Contacts database.

Instead of requesting for contact details in a SQL-like fashion, developers can use a strongly-typed API to query for the information they need. The following sample returns a contact's Structured Names and phone numbers:

val store = ContactStore.newInstance(application)

store.fetchContacts(
    predicate = ContactLookup(
        inContactIds = listOf(contactId)
    ),
    columnsToFetch = listOf(
        ContactColumn.NAMES,
        ContactColumn.PHONES
    )
)
    .collect { contacts ->
        val contact = contacts.firstOrNull()
        if (contact == null) {
            println("Contact not found")
        } else {
            val phones = contact.phones
            val contactString = contacts.joinToString(", ") { contact ->
                "Names = ${contact.firstName} ${contact.middleName} ${contact.lastName} " +
                        "phones = ${phones.map { "${it.value} (${it.label})" }}"
            }
            println("Contacts emitted: $contactString")
        }
    }
Enter fullscreen mode Exit fullscreen mode

Source code on Github

Your feedback is greatly appreciated 🙏 Follow me on Twitter for further updates

Top comments (0)