Kotlin: Get Android Contacts List Fast

Volkan YILMAZ
2 min readJul 1, 2020

--

Getting contacts can be used in several different applications such as music, contacts, and sticker applications. Today I will share my experience to retrieve and show contacts list in two ways: slower and faster methods in Kotlin. I have found several blogs and code examples on the Internet however I couldn’t know which one is more efficient until I tried some.

Let’s start with the slower method:

In slow method, I use RxJava to perform query in backgorund thread. Inside, I created a simple cursor for query and additional query for contact details.

I need lastHeader since I want to create headers for each letter A-Z. Thus, first ContactItemViewState object is for header and the second one is for a contact.

This method might fetch some contacts twice and therefore we need to check first before adding it to our list.

Finally, we need to close two cursors before the passing final list in onNext() method of Observable.

Here is the faster method:

Here we do not need the second cursor because our first query is more complex. Let’s look at it closer. First, I created string array of required column names for query to retrieve and we pass it to query as second argument. Third argument is a condition for selection. Contacts objects with phone numbers are valid. Finally, display_name ASC sorts the query results in ascending order with respect to contact names. We need it because we want to use headers before each letter A-Z. As cursor moves next, we get a new contact

So how is the performance if we evaluate two models. In terms of run time, first method gets and displays ~200 contacts in 5–6 seconds. That is not quite bad however it is annoying a little. Second method however, gets and displays ~200 contacts in just 1-1.5 seconds! It is 4 times better.

I used RxJava3 to perform this query in background process using disposable. To get the result array we need a disposable and in subscibe method we can get it like this:

I used progress bar animation for recyclerview while it is loading. You can get such animations very easily from here. Just add new layout and inside progress bar and when your list is ready to show up you can hide it.

When you exit you need to close the disposable to prevent memory leak:

Thank you for reading this article. I hope you enjoyed while reading and learn how to get contacts easily and fast for your projects!

--

--