While playing with Android, I wanted to get contact details from my contact list. I don’t know exactly why, but every type of contact (phone number, email, …) is stored on a different ContentProvider.
That is, you cannot get every contact detail using only one request. After some time looking for the best way to do it, I think I found something good, using no deprecated methods (like 90% of what I could see on the web). I guess it is the best solution
So, let’s dig into code!
First, don’t forget to request the permission to read contacts in AndroidManifest.xml:
1 | <uses-permission android:name="android.permission.READ_CONTACTS" /> |
We will then get every contact and their ID using one request. Same for the phone numbers
1 2 3 | ContentResolver cr = getContentResolver(); Cursor cCur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); |
We can then remember the names using their ID
1 2 3 4 5 6 7 | HashMap contacts = new HashMap(); while (cCur.moveToNext()) { String id = cCur.getString(cCur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); String name = cCur.getString(cCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); contacts.put(id, name); } |
After that we can match phone number with contacts