Home » Android » Android Contacts._ID != Data.CONTACT_ID

Android Contacts._ID != Data.CONTACT_ID

Posted by: admin June 15, 2020 Leave a comment


I’m running a query against CommonDataKinds.Phone.CONTENT_URI and I’m getting all the results that have a NOT NULL phone id.

pretty much the code is :

    String[] projection2 = new String[] {
    String where2 = ContactsContract.CommonDataKinds.Phone._ID + " != ''" ;

    Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection2, where2, null, null);

and then I iterate through each cursor result and getting the columns I want.
The code is :

           if (phoneCursor.getCount() > 0) {
            while (phoneCursor.moveToNext()) {
                String contacts_id = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.Contacts._ID));
                String phone_id = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    Log.i("phonecursor", "contacts_id= "  + contacts_id + " phone_id " + phone_id 
                            +  "  contacts_name= "  + contacts_name + " phone_name= " + phone_name
                            + " Phone= " + phone  );


What I dont get is why Phone.CONTACT_ID is different from the corresponding Contacts._ID from the same row…

Shouldn’t both be the same? There are a lot of examples that use those exact columns to run queries. For example here and here if you check the Key pointers.

How to&Answers:

ContactsContract.Contacts._ID returns unique ID for a row

this is very good example

and this image


ContactsContract.Contacts._ID returns unique ID for a row.

Now the output will vary based on which cursor you are querying ContactsContract.Contacts._ID.

If you query ContactsContract.Contacts._ID from ContactsContract.Contacts.CONTENT_URI , you will get ContactsContract.Contacts._ID and ContactsContract.CommonDataKinds.Phone.CONTACT_ID same.

But if you query ContactsContract.Contacts._ID from ContactsContract.CommonDataKinds.Phone.CONTENT_URI you will get ContactsContract.Contacts._ID and ContactsContract.CommonDataKinds.Phone.CONTACT_ID different as on each phone entry ContactsContract.Contacts._ID is incremented.

So if you want same _ID and Phone._ID then query from ContactsContract.Contacts.CONTENT_URI instead of ContactsContract.CommonDataKinds.Phone.CONTENT_URI