从Android 2.3.4中的号码获取联系人姓名
我试图在2.3.4安卓系统中使用数字获取联系人的姓名,但它不起作用。。这里我附上了我的代码。请帮忙。。我已经尝试了很多方法,如在Stack over flow中发布的,在emulator中工作,但在手机中运行时失败了从Android 2.3.4中的号码获取联系人姓名,android,Android,我试图在2.3.4安卓系统中使用数字获取联系人的姓名,但它不起作用。。这里我附上了我的代码。请帮忙。。我已经尝试了很多方法,如在Stack over flow中发布的,在emulator中工作,但在手机中运行时失败了 String[] projection = new String[] { Contacts.Phones.DISPLAY_NAME, Contacts.Phones.NUMBER }; // encode
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";
}
查看API以了解:
公共静态最终字符串数字
用户输入的电话号码
因此,您在程序中使用的号码必须与电话簿中的号码完全相同(逐个字符)。这可能是它在电话上失败的原因,因为您的电话簿可能包含国家代码信息,如+46xxxxxxxx
为了解决这个问题,use from it将使用一种算法来检查数字是否相等(同样,
Contacts.Phones
中的常量已弃用):
(如果找不到与该号码相关的联系人,此代码将返回该号码。)您可以更好地使用游标加载程序,这样主线程就不会被阻塞。获取索引然后获取字符串是不必要的
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();
}
}
您可以发布您的完整代码吗?如何从适配器传递或获取
ContentResolver cr
??
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();
}
}