[英]How to get contact id by phone number
我將手機的calllog查詢到ListView。 因此,當用戶長按一個項目時,會出現一個對話框,其中包括“查看聯系人”。 為了能夠查看聯系人意圖需要聯系人ID。 我的問題是,我並不總能看到正確的聯系方式。 我點擊彼得,彼得的聯系表出現了。 我點擊Sarah,Jason的聯系表出現了。
我一定是以錯誤的方式使用這段代碼。 請幫忙。
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cursor = contentResolver.query(uri, new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);
if(cursor!=null) {
while(cursor.moveToNext())
{
String contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
contactid2 = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup._ID));
}
cursor.close();
}
Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/" + contactid2));
startActivity(intent_contacts);
也許我需要的不是PhoneLookup._ID,而是其他一些ID。
我也試過菲利普的答案在這里 ,同樣的情況發生。
編輯:
這到底是怎么回事???
在深入了解主題后,我在googlegroups上找到了sven的幫助。 問題是我正在使用一個被剝奪的意圖。 我在開發者網站上閱讀了很多頁面,我一定錯過了它。
我也發布了完整的代碼。
contactid26 = null;
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phonenumintolist));
Cursor cursor =
contentResolver.query(
uri,
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
if(cursor!=null) {
while(cursor.moveToNext()){
String contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
contactid26 = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup._ID));
}
cursor.close();
}
if (contactid26 == null) {
Toast.makeText(DetailedCallHistory.this, "No contact found associated with this number", Toast.LENGTH_SHORT).show();
}
else {
Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactid26)));
//Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/" + contactid26));
startActivity(intent_contacts);
}
在這種情況下,我將向您展示如何獲取ID,以及您輸入並想要搜索的任何聯系人號碼,例如,如果輸入no並想要搜索其名稱和ID,則使用這段代碼,它是100%工作,如果你想進一步修改,那么你可以告訴我
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phnno.getText().toString()));//phone no
String[] proj = new String[]
{///as we need only this colum from a table...
Contacts.DISPLAY_NAME,
Contacts._ID,
};
String id=null;
String sortOrder1 = StructuredPostal.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor crsr = getContentResolver().query(lookupUri,proj, null, null, sortOrder1);
while(crsr.moveToNext())
{
String name=crsr.getString(crsr.getColumnIndex(Contacts.DISPLAY_NAME));
id = crsr.getString(crsr.getColumnIndex(Contacts._ID));
Toast.makeText(this,"Name of this cntct is : " +name +"\n id is : "+id ,Toast.LENGTH_SHORT).show();
}
crsr.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.