I wrote this function to retrieve contacts in android phones:
public static HashMap<String, Contact> getAllContacts(Context context) {
HashMap<String, Contact> contactsList = new HashMap<>();
if(!contactsReadPermission(context))
return contactsList;
DateTime timestamp = DateTime.now();
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.SORT_KEY_PRIMARY + " ASC");
if (cursor != null) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if (phoneNumber == null)
continue;
contactsList.put(phoneNumber, new Contact(name, phoneNumber, timestamp.toString()));
}
phoneCursor.close();
}
}
cursor.close();
}
return contactsList;
}
And this code works just fine in all android devices except for Xiaomi Phones. I figure this is probably am issue with MIUI devices.
This functions returns empty hash-map when I run it on a MIUI ROM.
The best thing is it will give you all unique contacts with Country code append
For kotlin you can use it like below
in this google phonelibnumber is used
Pojo or data class