How to get contact id by phone number
android, contacts
Solution
After digging myself into theme, I found sven's help on googlegroups. The problem was that I was using a depracated intent. I read through many pages on the developer site, I must have missed it somehow.
I also post the full code.
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);
}
Problem
I query the phone's calllog into a ListView. So when the user long clicks an item, a dialog comes up with options, including "View contact". To be able to view the contact the intent needs the contact id. My problem is that I not always get to see the right contact. I click on Peter, and Peter's contact sheet comes up. I click on Sarah, and Jason's contact sheet comes up. I must have been using this code the wrong way. Please help. ``` 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); ``` Maybe what I need is not the PhoneLookup._ID, but some other ID. I also tried Felipe's answer here, same happens. Edit: - on a HTC Desire HD (2.3.5) I get the proper contacts in 99% of the cases. - on a ZTE Blade (2.2) I get the proper contacts in 60% of the cases. - on a Samsung Galaxy Ace (2.3.3) I get the proper contacts in 5% of the cases. What the hell is going on???