2012-01-09 70 views
2

我嘗試使用2.3.4 android中的號碼獲取聯繫人的姓名,但它不工作..在這裏,我附上了我的代碼。請幫助..我已經試了很多方法如過流堆棧發佈,在模擬器它的工作,但同時手機的運行速度失敗..從Android 2.3.4號碼獲取聯繫人姓名

String[] projection = new String[] { Contacts.Phones.DISPLAY_NAME, 
            Contacts.Phones.NUMBER }; 

// encode the phone number and build the filter URI 
Toast.makeText(context, "sender: "+sender, Toast.LENGTH_LONG).show(); 

Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, 
             Uri.encode(sender)); 

// query time 
Cursor c = context.getContentResolver().query(contactUri, projection, null, 
               null, null); 

// if the query returns 1 or more results 
// return the first result 
if(c.getCount()>0){ 
    if (c.moveToFirst()) { 
     name = c.getString(c.getColumnIndex(Contacts.Phones.DISPLAY_NAME)); 
    }     
}else{ 
    name="UnKnown"; 
} 
+0

請問您可以發佈完整的代碼嗎? – swathi 2012-05-31 05:55:33

回答

4

在API尋找Contacts.Phones.NUMBER

公衆static final字符串NUMBER

用戶輸入的電話號碼。

所以你在程序中使用的數量必須指定完全相同(符號字符)作爲一個在電話簿。這可能是因爲您的電話簿可能包含國家/地區代碼信息,例如+46xxxxxxxx,因此它會在電話上失敗。

爲了解決這個問題,使用PhoneLookupContactsContract它將使用算法來檢查,如果數量相等(也 從Contacts.Phones常量已廢棄):

public static String getContactName(String num, ContentResolver cr) { 

    Uri u = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI Uri.encode(num)); 
    String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME}; 

    Cursor c = cr.query(u, projection, null, null, null); 

    try { 
     if (!c.moveToFirst()) 
      return number; 

     int index = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); 
     return c.getString(index); 

    } finally { 
     if (c != null) 
      c.close(); 
    } 
} 

(此代碼返回如果未找到與該號碼的聯繫人,則爲號碼。)

+0

感謝@dacwe,它現在的工作.. :-) – jerith 2012-01-09 09:27:11

+0

工作得很好.... – jerith 2012-01-09 09:27:36

+0

如何通過或從適配器獲取'ContentResolver cr'? – cheloncio 2014-03-19 19:47:07

0

您可以更好地使用光標加載器,以便主線程無法被阻止。得到索引然後得到字符串是不合適的。

private String getContactName(String num) { 

    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(num)); 
    String[] projection = new String[] {ContactsContract.Contacts.DISPLAY_NAME}; 

    CursorLoader cursorLoader = new CursorLoader(getActivity(), uri, projection, null, null,null); 

    Cursor c = cursorLoader.loadInBackground(); 

    try { 
     if (!c.moveToFirst()) 
      return num; 

     return c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
    } catch (Exception e) 
    { 
     Log.e(TAG,"Error looking up the contactname." + e); 
     return num; 
    } 
    finally { 
     if (c != null) 
      c.close(); 
    } 
} 
相關問題