Search code examples
androidandroid-contactscontactscontract

Android Contacts Contract: Is it possible to get unique id of data row?


So I know by now that Contacts are saved in three tables:

  • Contacts table.
  • Raw contacts table.
  • Data table.

The table that I am using:

I am using the data table to read users with all their phone numbers according to and thanks to @marmor in this answer.

What I got from the solution in the above link:

Using the answer provided by @marmor in the above link I was able to query (for all contacts in the phonebook) a contact_id mapped to a set of phone numbers for this specific contact.

Defining contact_id & set of phone numbers:

  • contact_id: Is the id of a contact in the phone book that can contain multiple types of linked accounts.

  • set of phone numbers: Is a set containing all phone numbers of a specific contact_id.

Problem:

Let's say I have two users X and Y :

user x has a contact_id = 0.

user y has a contact_id = 1.

Now let's say user x has these numbers linked: +1111-xxx and +2222-xxx

And let's say user y has these numbers linked: +3333-xxx and +2222-xxx

Now I decide to save all these numbers to the local database on the phone:

case 1:

If I used the numbers of these users as the main id to save into database then +2222-xxx in user x will overwrite +2222-xxx in user y.

case 2:

If I used the contact_id as the main id to save into database then +1111-xxx and +2222-xxx that corresponds to the same user_id (0) will both be overwritten so one will win.

case 3:

If used a combination of phone number + contact_id as the main id to save into database then as it might work it seems not the very clean solution and not stable.

Question:

Is it possible to get a unique id that identifies each number found in the contact_id?

Thanks.


Solution

  • A. It is definitely possible to get a Data row id:

    When querying over Data.CONTENT_URI, just add Data._ID to your projection, and you can then get the specific Data ID and do whatever you want with it.

    B. Is it wise to persist the Data ID into your DB as the key of a contact/number combo? No.

    Data IDs can change over time, and are not guaranteed to be consistent, so it's highly discouraged to persist it into a local DB, and use it as a long-running identifier.

    C. What you can do instead?

    Use the E164 phone number as your key, as this is something static that can't change, a contact may gain or lose a phone number with its contact info, but the phone number is still the same phone number.

    Just allow a one-to-many connection between your key - the phone number - and the contacts. So a single phone number X can point to 0 or more different contacts that currently have that number in their data rows.

    You'll need to run periodically (e.g. once a day) to refresh your internal DB with changes from the device's contacts DB.