Wednesday, December 7, 2011

Query contact name by phone number (Android)

   1: public static String queryNamebyNumber(ContentResolver cr,String number)
   2: {
   3:     String[] projection = new String[] {
   4:             ContactsContract.PhoneLookup.DISPLAY_NAME,  
   5:             ContactsContract.CommonDataKinds.Phone.NUMBER
   6:          }; 
   7:  
   8:     // Make the query. 
   9:     Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
  10:                              ,projection // Which columns to return
  11:                              ,ContactsContract.CommonDataKinds.Phone.NUMBER + "=?"
  12:                              ,new String[]{number}
  13:                              ,null);
  14:     
  15:     String numberOwner = "";
  16:      if (cur.moveToFirst()) 
  17:      {
  18:         int nameColumn = cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME); 
  19:         do {
  20:             String name = cur.getString(nameColumn);               
  21:             if (name != null)
  22:                 numberOwner += (name + "|||");
  23:         } while (cur.moveToNext());            
  24:      }
  25:      Logger.d(TAG, "number owner:" + numberOwner);
  26:      
  27:     cur.close();
  28:     return numberOwner;
  29: }

Something we should care, the format symbol:


When a contact was synced from Google Contacts, the phone number within the contact was totally same as you typed in Google Contacts. No “-” would been added! number “4081234567” will not be formatted to “408-123-4567”!


While you add a contact on the phone(maybe some models), when you type “4081234567”. “408-123-4567” will saved as the number.


So, if you’re going to make a smart phone number query, you’d better process the “-” symbol.

No comments:

Post a Comment