title: How to get contact id by phone number
body: <p>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.</p>
  
  <p>I must have been using this code the wrong way. Please help.</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>Maybe what I need is not the PhoneLookup._ID, but some other ID.</p>
  
  <p>I also tried Felipe's answer <a href="https://stackoverflow.com/questions/3712112/search-contact-by-phone-number">here</a>, same happens.</p>
  
  <p><strong>Edit:</strong></p>
  
  <ul>
  <li>on a HTC Desire HD (2.3.5) I get the proper contacts in 99% of the
  cases.</li>
  <li>on a ZTE Blade (2.2) I get the proper contacts in 60% of the cases.</li>
  <li>on a Samsung Galaxy Ace (2.3.3) I get the proper contacts in 5% of the cases.</li>
  </ul>
  
  <p>What the hell is going on???</p>