3

I'm creating an Sms app which contains a ListView in the Main Activity that displays all the conversations from the sms inbox. Each ListView row displays one conversation along with the phone number, message body and time of the message. Now instead of the phone number I want to display the contact name if it exists.

So far, for getting the 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 inefficient as it has to make a query for each contact name individually and lags the app. So instead I tried to get all the contact names from the phone and store it in an HashMap with the phone number as the key and the contact name as the value, so that I can get the contact name any time I want from the HashMap. But there seems to be another problem, the phone numbers are stored in many different formats, for eg:

+91 4324244434
04324244434
0224324244434

So how do I search for a phone number from the HashMap since it can be stored in many different formats?

Sam
  • 75
  • 2
  • 7

1 Answers1

0

Before you add the contact to the HashMap, use regular expression to grab the phone number. This way, no matter what format the phone number is in, the regular expression will be able to grab the appropriate number needed.

Once you grab the number, add it to the HashMap accordingly.

Hope that answers your question.

Rob Avery IV
  • 3,562
  • 10
  • 48
  • 72
  • I think the phone numbers can be stored in vast different formats, creating one Regex for it may be difficult. Do you have any idea how the Android library(code posted in the question) searches for the phone number and always gives the exact match? – Sam Jan 25 '13 at 15:58
  • @Sam sorry, i can't help you in that department. Try looking at Google's Android resoruces at http://developer.android.com/training/index.html. Also, this might be a related question also: http://stackoverflow.com/questions/3079365/android-retrieve-contact-name-from-phone-number – Rob Avery IV Jan 25 '13 at 16:02