Skip to content

Instantly share code, notes, and snippets.

@antarikshc
Last active May 19, 2019 08:05
Show Gist options
  • Save antarikshc/f2727d087aa2355dcba0f553a71056cd to your computer and use it in GitHub Desktop.
Save antarikshc/f2727d087aa2355dcba0f553a71056cd to your computer and use it in GitHub Desktop.
Snippet for fetching contacts in Android
// Declare the data class in Contact.kt
data class Contact(
val id: String,
val name: String,
val thumbnailUri: String?
)
// Following code goes into Fragment or Activity file
// This snippet is used in Android Fragments. Change it accordingly for using it in Activities
// Declare in Global scope before class declaration
private val PROJECTION: Array<out String> = arrayOf(
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
)
class .... : Fragment(), CoroutineScope {
// Global params
// Coroutine
private lateinit var mJob: Job
override val coroutineContext: CoroutineContext
get() = mJob + Dispatchers.Main
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Launch Coroutine to retrieve Contacts
mJob = Job()
launch {
val contacts: ArrayList<Contact> = ArrayList()
// Switch context to run on Background Thread
val deferred = async(Dispatchers.Default) {
val cursor = getContacts()
cursor?.let {
if (cursor.count > 0) {
while (cursor.moveToNext()) {
val id = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts._ID)
)
var name = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
)
if (name == null) {
name = "Unknown"
}
val thumbUri = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI)
)
contacts.add(Contact(id, name, thumbUri))
}
}
}
}
deferred.await()
// Contacts are saved in contacts array
// For eg: setupContactsAdapter(contacts)
}
}
/**
* Use Content Resolver to retrieve contacts
*/
private fun getContacts(): Cursor? {
val contentResolver = activity?.contentResolver
contentResolver?.let {
return it.query(
ContactsContract.Contacts.CONTENT_URI,
PROJECTION,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
)
}
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment