Android get contact names by phone number efficiently for display in ListView
I am creating an Sms application containing ListView
in main activity that displays all conversations from nested sms messages. Each line ListView
displays one conversation along with the phone number, message body and message time. Now, instead of the phone number, I want to display the contact's name if it exists.
So far for getting contact name by phone number I found this code
private String getDisplayNameByNumber(String number) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor contactLookup = context.getContentResolver().query(uri, new String[] {ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
int indexName = contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
try {
if (contactLookup != null && contactLookup.moveToNext()) {
number = contactLookup.getString(indexName);
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return number;
}
But this seems ineffective as it has to query for each contact name individually and lag behind the application. So instead I tried to get all the contact names from the phone and store them in HashMap
with the phone number as the key and the contact name as the value so that I can get the contact name anytime I want to get from HashMap
. But there seems to be another problem, phone numbers are stored in different formats, for example:
+91 4324244434
04324244434
0224324244434
So how do I search for a phone number from HashMap
, since it can be saved in different formats?
source to share
Before adding a contact to HashMap
, use a regular expression to capture the phone number. This way, regardless of the format the phone number is in, the regex will be able to capture the required amount.
Once you get the number, add it in HashMap
accordingly.
Hope that answers your question.
source to share