Search code examples
javaandroidandroid-intentandroid-cursor

Obtain the same ID from the contact picker and cursor


I'm using a contact picker as such:

startActivityForResult(
    new Intent(
        Intent.ACTION_PICK,
        Phone.CONTENT_URI
    ), CONTACT_PICKER_RESULT //1001
);

This type of contact picker picks out a specific phone number that a contact has.

I then get an ID for this contact with:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode != CONTACT_PICKER_RESULT || resultCode != RESULT_OK)
        return;

    String id = data.getData.getLastPathSegment();
}

However, when I use a PhoneLookup query, such as:

Cursor cur = getContentResolver().query(
    Uri.withAppendedPath(
        PhoneLookup.CONTENT_FILTER_URI,
        Uri.encode(...) //phone number of contact is filled in
    ),
    new String[] {
        PhoneLookup.DISPLAY_NAME,
        Phone._ID
    }, null, null, null
);

if (!cur.moveToFirst())
    return;

String id = cur.getString(
    cur.getColumnIndex(Phone._ID)
);

The ID I get from the PhoneLookup is different from the onActivityResult. For example, the contact picker returns 1408 while the cursor returns 444.

How can I get:

data.getData().getLastPathSegment() equal to cur.getColumnIndex(...)?


Solution

  • You can't use a PhoneLookup in this case. You need to query Phone.CONTENT_URI to obtain the ID that matches up with the contact picker. The following code below does exactly this.

    Cursor cur = getContentResolver().query(
        Phone.CONTENT_URI,
        new String[] {
            Phone.DISPLAY_NAME,
            Phone._ID
        },
        Phone.NORMALIZED_NUMBER + "=?",
        new String[] {
            ... //phone number placed here
        }, null);
        if (!cur.moveToFirst())
            return;
    
    String id = cur.getString(cur.getColumnIndex(Phone._ID)));