Search code examples
androidcontactsandroid-contactsandroid-contentresolver

How to get the contact from the CONTENT URI


I add a custom contact raw to my contacts from my app (like in whatsapp). When I click the custom raw, it open my app. In my viewing activity I check the action and get the content URI from getIntent().getDataString(). It gives me this - content://com.android.contacts/data/10399. Now I want to get the contact details from this URI. But when I check my contact list using the following code.

void checkContacts(Context context) {
    Cursor cursor = context.getContentResolver().query(
            ContactsContract.Data.CONTENT_URI,
            null,
            null, null, null);
    if (cursor != null) {
        Log.e(TAG, String.valueOf(cursor.getCount()));
        try {
            while (cursor.moveToNext()) {
                Log.e(TAG, cursor.getString(cursor
                        .getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID)));
                Log.e(TAG, "** " + cursor.getString(cursor
                        .getColumnIndexOrThrow(ContactsContract.Data.RAW_CONTACT_ID)));
            }
        } finally {
            cursor.close();
        }
    }
}

But i couldn't find any CONTACT_ID or RAW_CONTACT_ID related to 10399. So how do I get the contact detail from this URI? I don't want to get all the contacts. I want to get the specific contact related to the URI.


Solution

  • try something like this

    Uri uri = data.getData();
    String[] projection = {
        ContactsContract.CommonDataKinds.Phone.NUMBER, 
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME 
    };
    
    Cursor cursor = getApplicationContext().getContentResolver().query(uri, projection,
        null, null, null);
    cursor.moveToFirst();
    
    int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    String number = cursor.getString(numberColumnIndex);
    
    int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
    String name = cursor.getString(nameColumnIndex);
    
    cursor.close();