2009
08.10

As a new feature in my Android app for the belgian mobile phone carrier Mobile Vikings I wanted to display contact names in the call history instead of the number. After a bit of googling I found that Android provides a few contentproviders holding the data I needed (contact names and phone numbers).

In a first attempt I retrieved all contacts with a simple query on the Contacts.Phone contentprovider, manually looped over the results and compared each number with the number I wanted to replace. This worked only when the number on the phone was stored exactly in the same format as the Mobile Vikings API returned it. If the Mobile Vikings api returned the number with the area code and the number was stored on the phone without the area code, no match was found.

After trying to figure out how I could get both numbers in the same format for comparison I figured out that Android provided a mechanism to do this. I could encode a phone number string into a filter URI provided by the Contacts.Phones contentprovider and use that filter to query on.

The code looks like this

	private String getContactNameFromNumber(String number) {
		// define the columns I want the query to return
		String[] projection = new String[] {
				Contacts.Phones.DISPLAY_NAME,
				Contacts.Phones.NUMBER };
 
		// encode the phone number and build the filter URI
		Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(number));
 
		// query time
		Cursor c = getContentResolver().query(contactUri, projection, null,
				null, null);
 
		// if the query returns 1 or more results
		// return the first result
		if (c.moveToFirst()) {
			String name = c.getString(c
					.getColumnIndex(Contacts.Phones.DISPLAY_NAME));
			return name;
		}
 
		// return the original number if no match was found
		return number;
	}

The result looks like this

contactnames

Share this article
  • Digg
  • Facebook
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Twitter

1 comment so far

Add Your Comment
  1. lpvcYF latipkpnbkle, [url=http://locxlcusemog.com/]locxlcusemog[/url], [link=http://qilhfpncbjrl.com/]qilhfpncbjrl[/link], http://gbhkgzcytysp.com/