我有以下代码.
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query( Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(contactNumber)), new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},null,null,null);
try
{
contactLookupCursor.moveToFirst();
while(contactLookupCursor.moveToNext())
{
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
}
}
finally
{
contactLookupCursor.close();
}
上述代码中的问题是,即使我在模拟器联系人中提供现有号码,它也不会返回任何结果.我在一小时前测试它,它工作正常,现在当我再次测试它时,它没有返回任何东西.我不确定代码是否有问题.我想要做的是获得一个与多个数字相匹配的 ID.例如,假设有一个名为A"的联系人姓名,而 A 有两个号码.基本上,无论我指的是哪个号码,A 的联系人 ID 都应该是 1.我的假设正确吗?
The problem in the above code is that even if I give a existing number in emulator contacts, its not returning any results. I was testing it an hour back and it was working fine, and now when I tested it again, its not returning anything. I am not sure if anything is wrong with the code. What I am trying to do is get a ID that matches a single with multiple numbers. For instance say there is a contact name called "A" and A has two numbers. Essentially the contact ID for A should be 1 regardless of which number I refer to. Is my assumption correct ?
更新:我做了更多的测试.假设如果在联系人数据库中存储的号码没有国家代码,例如 222-222-2222.仅当我通过 2222222222 或 222-222-2222 时,使用以下代码进行的搜索才会返回联系人 ID.如果存储相同的号码,如 12222222222,则只有当我搜索号码为 12222222222 时才会收到有效的联系人 ID.
UPDATE : I did some more tests. Let's say if a number is stored without the country code in the contacts database like 222-222-2222. A search using the below code returns contact id only when I pass 2222222222 or 222-222-2222. And if the same number is stored like 12222222222 a valid contact id is received only if I search number is 12222222222.
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone._ID,ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
Uri contactUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(contactNumber));
Cursor c = context.getContentResolver().query(contactUri, projection, null, null, null);
if (c.moveToFirst()) {
phoneContactID = c.getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
}
我不确定我是否在这里做错了什么.任何帮助将不胜感激.
I am not sure if I am doing something wrong here. Any help would be appreciated.
public static int getContactIDFromNumber(String contactNumber,Context context)
{
contactNumber = Uri.encode(contactNumber);
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,contactNumber),new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext()){
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
现在正在运行的代码.
这篇关于从 Android 联系人数据库获取联系人 ID 未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!