Android Contacts API Library written in Kotlin with Java interoperability. No more ContentProviders and cursors. Say goodbye to ContactsContract. Build your own contacts app!
FreeWritten with â¥ï¸ and ð¥ since December 2018. Open sourced since October 2021.
This library provides a complete set of APIs to do everything you need with Contacts in Android. You no longer have to deal with the Contacts Provider, database operations, and cursors.
Whether you just need to get all or some Contacts for a small part of your app (written in Kotlin or Java), or you are looking to create your own full-fledged Contacts app with the same capabilities as the AOSP Android Contacts app and Google Contacts app, this library is for you!
Please help support this project ðâ¤ï¸âï¸
The core
module provides,
There are also extensions that add functionality to every core function,
Also included are some pre-baked goodies to be used as is or just for reference,
There are also more features that are on the way!
â¹ï¸ This library is a multi-module project published with JitPack
First, include JitPack in the repositories list,
repositories {
maven { url "https://jitpack.io" }
}
To install individual modules,
dependencies {
implementation 'com.github.vestrel00.contacts-android:core:0.3.1'
implementation 'com.github.vestrel00.contacts-android:async:0.3.1'
implementation 'com.github.vestrel00.contacts-android:customdata-gender:0.3.1'
implementation 'com.github.vestrel00.contacts-android:customdata-googlecontacts:0.3.1'
implementation 'com.github.vestrel00.contacts-android:customdata-handlename:0.3.1'
implementation 'com.github.vestrel00.contacts-android:customdata-pokemon:0.3.1'
implementation 'com.github.vestrel00.contacts-android:customdata-rpg:0.3.1'
implementation 'com.github.vestrel00.contacts-android:debug:0.3.1'
implementation 'com.github.vestrel00.contacts-android:permissions:0.3.1'
implementation 'com.github.vestrel00.contacts-android:test:0.3.1'
implementation 'com.github.vestrel00.contacts-android:ui:0.3.1'
// Notice that when importing specific modules/subprojects, the first ":" comes after "contacts-android".
}
The core
module is really all you need. All other modules are optional.
To install all modules in a single line,
dependencies {
implementation 'com.github.vestrel00:contacts-android:0.3.1'
// Notice that when importing all modules, the first ":" comes after "vestrel00".
}
â ï¸ Starting with version 0.2.0, installing all modules in a single line is only supported when using the
dependencyResolutionManagement
insettings.gradle
. You are still able to install all modules by specifying them individually.
For more info about the different modules and dependency resolution management, read the Installation guide.
There is no setup required. It's up to you how you want to create and retain instances of the
contacts.core.Contacts(context)
API. For more info, read Contacts API Setup.
It is also useful to read about API Entities.
To retrieve all contacts containing all available contact data,
val contacts = Contacts(context).query().find()
To simply search for Contacts, yielding the exact same results as the AOSP Contacts app,
val contacts = Contacts(context)
.broadQuery()
.wherePartiallyMatches(searchText)
.find()
â¹ï¸ For more info, read Query contacts.
Something a bit more advanced...
To retrieve the first 5 contacts (including only the contact id, display name, and phone numbers in the results) ordered by display name in descending order, matching ALL of these rules;
val contacts = Contacts(context)
.query()
.where {
(Name.GivenName startsWith "leo") and
(Email.Address { endsWith("gmail.com") or endsWith("hotmail.com") }) and
(Address.Country equalToIgnoreCase "us") and
(Event { (Date lessThan Date().toWhereString()) and (Type equalTo EventEntity.Type.BIRTHDAY) }) and
(Contact.Options.Starred equalTo true) and
(Nickname.Name equalTo "DarEdEvil") and
(Organization.Company `in` listOf("facebook", "FB")) and
(Note.Note.isNotNullOrEmpty())
}
.accounts(
Account("john.doe@gmail.com", "com.google"),
Account("john.doe@myspace.com", "com.myspace"),
)
.include { setOf(
Contact.Id,
Contact.DisplayNamePrimary,
Phone.Number
) }
.orderBy(ContactsFields.DisplayNamePrimary.desc())
.offset(0)
.limit(5)
.find()
â¹ï¸ For more info, read Query contacts (advanced).
Once you have the contacts, you now have access to all of their data!
val contact: Contact
Log.d(
"Contact",
"""
ID: ${contact.id}
Lookup Key: ${contact.lookupKey}
Display name: ${contact.displayNamePrimary}
Display name alt: ${contact.displayNameAlt}
Photo Uri: ${contact.photoUri}
Thumbnail Uri: ${contact.photoThumbnailUri}
Last updated: ${contact.lastUpdatedTimestamp}
Starred?: ${contact.options?.starred}
Send to voicemail?: ${contact.options?.sendToVoicemail}
Ringtone: ${contact.options?.customRingtone}
Aggregate data from all RawContacts of the contact
-----------------------------------
Addresses: ${contact.addressList()}
Emails: ${contact.emailList()}
Events: ${contact.eventList()}
Group memberships: ${contact.groupMembershipList()}
IMs: ${contact.imList()}
Names: ${contact.nameList()}
Nicknames: ${contact.nicknameList()}
Notes: ${contact.noteList()}
Organizations: ${contact.organizationList()}
Phones: ${contact.phoneList()}
Relations: ${contact.relationList()}
SipAddresses: ${contact.sipAddressList()}
Websites: ${contact.websiteList()}
-----------------------------------
""".trimIndent()
// There are also aggregate data functions that return a sequence instead of a list.
)
â¹ï¸ For more info, read about API Entities.
This library is capable of doing more than just querying contacts. Actually, you can build your own full-fledged contacts app with it!
Let's take a look at a few other APIs this library provides...
To get the first 20 gmail emails ordered by email address in descending order,
val emails = Contacts(context)
.data()
.query()
.emails()
.where { Email.Address endsWith "gmail.com" }
.orderBy(Fields.Email.Address.desc(ignoreCase = true))
.offset(0)
.limit(20)
.find()
It's not just for emails. It's for all data kinds (including custom data).
â¹ï¸ For more info, read Query specific data kinds.
To CREATE/INSERT a contact with a name of "John Doe" who works at Amazon with a work email of "john.doe@amazon.com" (in Kotlin),
val insertResult = Contacts(context)
.insert()
.rawContacts(NewRawContact().apply {
name = NewName().apply {
givenName = "John"
familyName = "Doe"
}
organization = NewOrganization().apply {
company = "Amazon"
title = "Superstar"
}
emails.add(NewEmail().apply {
address = "john.doe@amazon.com"
type = EmailEntity.Type.WORK
})
})
.commit()
Or alternatively, in a more Kotlinized style using named arguments,
val insertResult = Contacts(context)
.insert()
.rawContacts(NewRawContact(
name = NewName(
givenName = "John",
familyName = "Doe"
),
organization = NewOrganization(
company = "Amazon",
title = "Superstar"
),
emails = mutableListOf(NewEmail(
address = "john.doe@amazon.com",
type = EmailEntity.Type.WORK
))
))
.commit()
Or alternatively, using extension functions,
val insertResult = Contacts(context)
.insert()
.rawContact {
setName {
givenName = "John"
familyName = "Doe"
}
setOrganization {
company = "Amazon"
title = "Superstar"
}
addEmail {
address = "john.doe@amazon.com"
type = EmailEntity.Type.WORK
}
}
.commit()
â¹ï¸ For more info, read Insert contacts.
If John Doe switches jobs and heads over to Microsoft, we can UPDATE his data,
Contacts(context)
.update()
.contacts(johnDoe.mutableCopy {
setOrganization {
company = "Microsoft"
title = "Newb"
}
emails().first().apply {
address = "john.doe@microsoft.com"
}
})
.commit()
â¹ï¸ For more info, read Update contacts.
If we no longer like John Doe, we can DELETE him from our life,
Contacts(context)
.delete()
.contacts(johnDoe)
.commit()
â¹ï¸ For more info, read Delete Contacts.
This library provides Kotlin coroutine extensions in the permissions
module for all API functions
to handle permissions and async
module for executing work in background threads.
launch {
val contacts = Contacts(context)
.queryWithPermission()
...
.findWithContext()
val deferredResult = Contacts(context)
.insertWithPermission()
...
.commitAsync()
val result = deferredResult.await()
}
â¹ï¸ For more info, read Permissions handling using coroutines and Execute work outside of the UI thread using coroutines.
So, if we call the above function and we don't yet have permission. The user will be prompted to give the appropriate permissions before the query proceeds. Then, the work is done in the coroutine context of choice (default is Dispatchers.IO). If the user does not give permission, the query will return no results.
â¹ï¸ Extensions for Kotlin Flow and RxJava are also in the project roadmap, which includes APIs for listening to Contacts database changes.
The above examples barely scratches the surface of what this library provides. For more in-depth
documentation, visit the GitHub Pages. For a sample app reference, take a look at
and run the sample
module.
Some other APIs or util functions out there typically perform one internal database query per contact returned. They do this to fetch the data per contact. This means that if there are 1,000 matching contacts, then an extra 1,000 internal database queries are performed! This is not cool!
To address this issue, the query APIs provided in the Contacts, Reborn library, perform only at least two internal database queries no matter how many contacts are matched! Even if there are 10,000 contacts matched, the library will only perform two internal database queries (depending on your query parameters). Fetch 10,000 contacts as fast as 99 milliseconds (varies per device)!
â¹ï¸ For more info, read Optimizing queries.
Of course, if you don't want to fetch all hundreds of thousands of contacts, the query APIs support
pagination with limit
and offset
functions!
Cancellations are also supported! To cancel a query amid execution,
.find { returnTrueIfQueryShouldBeCancelled() }
The find function optionally takes in a function that, if it returns true, will cancel query processing as soon as possible. The function is called numerous times during query processing to check if processing should stop or continue. This gives you the option to cancel the query.
This is useful when used in multi-threaded environments. One scenario where this would be frequently used is when performing queries as the user types a search text. You are able to cancel the current query when the user enters new text.
For example, to automatically cancel the query inside a Kotlin coroutine when the coroutine is cancelled,
launch {
withContext(coroutineContext) {
val contacts = query.find { !isActive }
}
// Or, using the coroutine extensions in the async module...
val contacts = query.findWithContext()
}
The API does not and will not force you to use any frameworks (e.g. RxJava or Coroutines/Flow)!
All core functions of the API live in the core
module, which you can import to your project all by
itself. Don't believe me? Take a look at the dependencies in the core/build.gradle
:D
So, feel free to use the core API however you want with whatever libraries or frameworks you want, such as Reactive, Coroutines/Flow, AsyncTask (hope not), WorkManager, and whatever permissions handling APIs you want to use.
All other modules in this library are optional and are just there for your convenience or for reference.
I also made sure that all core functions and entities are interoperable with Java. So, if you were wondering why Iâm using a semi-builder pattern instead of using named arguments with default values, that is why. Iâve also made some other intentional decisions about API design to ensure the best possible experience for both Kotlin and Java consumers without sacrificing Kotlin language standards. It is Kotlin-first, Java-second (with love and care).
â ï¸ Modules other than the core module are not guaranteed to be compatible with Java.
If you use Proguard and the async
and/or permissions
modules, then you may need to add rules for
Coroutines.
Copyright 2023 Contacts Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.