从Android 2.3.4号码获取联系人姓名

问题描述:

我尝试使用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

在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

您可以更好地使用光标加载器,以便主线程无法被阻止。得到索引然后得到字符串是不合适的。

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(); 
    } 
}