https://stackoverflow.com/questions/5151885/android-new-data-record-is-added-to-the-wrong-contact/5158059#5158059
https://developer.android.com/guide/topics/providers/contacts-provider.html
https://stackoverflow.com/questions/35448250/how-to-get-whatsapp-contacts-from-android/35453979#35453979
https://developer.android.com/reference/android/provider/ContactsContract.RawContactsEntity.html
https://developer.android.com/reference/android/provider/ContactsContract.Data.html
Couple of Key pointers:
- Contacts._ID = Data.CONTACT_ID
- RawContacts._ID = Data.RAW_CONTACT_ID
- RawContacts.CONTACT_ID = Contacts._ID
- RawContactsEntity._ID = RawContacts._ID
Sounds confusing?? Let me try...
- The Contacts database is divided into 3 tables contacts, raw contacts, and data.
- Each table contains column (_ID) which is an auto incremented primary key.
- data table contains all the contact info like phone number, mail id, address etc.
- The raw contacts points to the actual contact created. Hence we use the raw contacts while adding a contact.
- The user cannot add any data in the contacts table. The data in this table is populated internally due to aggregation of contacts.
- The reason your logic worked for some of the contacts is: _ID for contacts, raw contactsremains same until there is any contact aggregation taking place. Lets say you add two contacts with same name abc. Here the _ID for raw contacts increments twice while _ID forcontacts increments only once as these two contacts gets merged due to the aggregation of contacts
Refer this for more details.
The best approach to fetch the info in your case is by using ContactsContract.RawContactsEntity
( an outer join of the raw_contacts table with the data table)
Reference:http://developer.android.com/reference/android/provider/ContactsContract.RawContactsEntity.html
here is the show Android Contact Data Store Diagram