2012-04-07 148 views
0

假設我有一個編輯文本和一個按鈕。在編輯文本中,您可以輸入一個數字,然後當您點擊該按鈕時,它將顯示聯繫信息或返回該聯繫人的姓名。從號碼獲取聯繫人姓名

我已經嘗試了各種方法提供沒有運氣。我成功地獲得了最遠的一個是以下...但我沒有運氣返回這個名字。

Cursor phoneCursor = null; 
    contactList = new HashMap<String,String>(); 

    try{ 
     Uri uContactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 

     String strProjection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME; 

     phoneCursor = getContentResolver().query(uContactsUri, null, null, null, strProjection); 
     phoneCursor.moveToFirst(); 

     String name = ""; 
     String phoneNumber = ""; 

     int nameColumn = phoneCursor.getColumnIndex(Phone.DISPLAY_NAME); 
     int phoneColumn = phoneCursor.getColumnIndex(Phone.NUMBER); 



      phoneCursor.moveToNext(); 

     } 
    } 
    catch(Exception e){ 
     Log.e("[SmsMain] getContactData", e.toString()); 
    } 
    finally{ 
     if(phoneCursor != null){ 
      phoneCursor.close(); 
      phoneCursor = null; 
     } 
    } 
} 

回答

0

使用下面的方法來獲取聯繫人姓名和號碼是否存在亙古不變的,而不是名稱返回相同的數字。

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; 
    } 
0

對於您需要使用優化PhoneLookup提供商所描述here

烏里URI = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber的)); 遊標cursor = resolver.query(uri,new String [] {PhoneLookup.DISPLAY_NAME},null,null,null);

請參閱本LINK瞭解更多詳情

相關問題