CONTACT_ID - Keeping it in sync - android

I am interested in your opinions on the best way to keep a robust reference to a contact starting android 2.0. I have read a lot regarding this issue but i don't know which technique is advisable and if there's any new ones. Below are the 3 options i found so far:
1- Don't use your own db. Extend the contacts.contract to write your data
2 - Use ContentObserver to keep track of any changes made to the contacts. This technique would however require your application to be running
3- Store all RAW contact IDs related to a CONTACT_ID in your db and infer the content of the aggregate contact from all its constituent RAW contacts
In my case i need to keep a separate db and i was wondering if there's any other new technique of keeping the CONTACT_ID current after aggregations and dis-aggregations...
Please advise

I am playing with the new Contacts API at the moment, writing an app which is also a source of contact data. I can't recommend #3 at all. To get all of "my" contact data I simply store them with a magic value in the RawContacts.SYNC1 field and query the contacts content provider for that when my app starts up.
Re. your question, don't use CONTACT_IDs, as they are volatile. Use the lookup API, i.e. if you have a raw contact ID, use RawContacts.getContactLookupUri() to get to the Contact. Likewise if some API gives you a contact ID, use Contacts.getLookupUri() to get a persistent identifier you can use later on.

Related

How apps like Truecaller, messenger maintains sync with native contacts application if any contact changes in the native contact app

I have observed if we update/delete a the contact in native contacts application same changes is reflected into the TrueCaller instantly.
I can think of two ways it get the changes:
It refresh the whole contact list by deleting all the existing entries in app and query all the entries from native contact using contact provider every time app comes to foreground.But this approach might involve querying the RawContact table and Data table on every launch. (This might be a costly in terms of computation)
Each raw contact maintains VERSION which increments if any change is made to the raw contact via native app. This can be leveraged for modifications but will require to maintain the old values in the truecaller(or similar app) so that we can compare.This approach will still require you query the RawContacts table.
The later approach requires to maintain the Version on the TrueCaller app database as well.
Following operations will be required to detect any changes :
Check the version of the raw contact in the TrueCaller if the version is less than that of raw contact in native contacts db, then, query the corresponding Data table for all the changes.
If any raw contact is deleted from native then it's either removed from the RawContact table or marked Deleted. Thus we need to check for Deleted flag or if any pervious RawContact entry is missing in the RawContact table.
Other cases like a new contact is added hence a new raw contact entry in the RawContact table will be found etc.
Is there any better way to import the contact in your app and maintain proper synchronization if any operation like addition, deletion or modification is performed in the native app?
Certainly, app like TrueCaller does a great job with this. Any article on import contacts etc any relevant source will be appreciated.
As apps such as TrueCaller are closed source, there's no way to give you a definite answer, however option 2 would be my course of action to manage the sync with the device contacts.
You can add to that ContentObserver on the ContactsContract ContentProvider which will call your code whenever something changes so you can run the suggested code at option 2, however note that contacts tend to change very very very frequently, so I would limit such background syncs if they are needed to once a day to prevent hogging the battery/CPU.

Should I rely on SOURCE_ID when reading Android Contacts?

I am creating an android contacts app, so I regularly read user's contacts and store them in my app. To do this, I need to rely on some kind of ID so that I know which contact I should update (or add/delete) in my app and Contacts Provider supplies several of them:
CONTACT_ID is the aggregate contact id,
each aggregate contact consists of one or more Raw Contacts, each with its own RAW_CONTACT_ID,
and most important, each Raw Contact has a SOURCE_ID, which is supposed to be the server id, i.e. the id this contact has in this account's server.
I 've chosen to rely on SOURCE_ID, since this sounds like the most stable one. E.g. when user removes and re-adds the same account in their device, I wouldn't want this account's contacts to get different IDs, because I wouldn't be able to match them in my app.
However, only Gmail sync adapter seems to keep the promise documented below. Exchange sync adapters unfortunately do not, SOURCE_ID changes, and it's definitely not any server id, since it has a small number like 23:4.
Question: Any ideas how to overcome this problem? Am I using the right ID for the intended use? Does exchange adapter stores the "permanent server id" in some other field?
Documentation: The SOURCE_ID must be unique for each account type and should be stable across syncs:
Unique: Each raw contact for an account must have its own source id. If you don't enforce this, you'll cause problems in the contacts
application. Notice that two raw contacts for the same account type
may have the same source id. For example, the raw contact "Thomas
Higginson" for the account emily.dickinson#gmail.com is allowed to
have the same source id as the raw contact "Thomas Higginson" for the
account emilyd#gmail.com.
Stable: Source ids are a permanent part of the online service's data for the raw contact. For example, if the user clears Contacts Storage
from the Apps settings and re-syncs, the restored raw contacts should
have the same source ids as before. If you don't enforce this,
shortcuts will stop working.
LOOKUP_KEY is what you're looking for.
LOOKUP_KEY
An opaque value that contains hints on how to find the
contact if its row id changed as a result of a sync or aggregation.
You should use a pair of <CONTACT_ID, LOOKUP_KEY> to keep track of contacts.
In normal use, use the CONTACT_ID value, but if your code gets a hint that the CONTACT_ID has changed (either missing, or unexpected contact name), you can use the LOOKUP_KEY to find the new contact-id.
Or you can use Contacts.getLookupUri() to get a URI you can always use to quickly find a contact no matter what its CONTACT_ID or LOOKUP_KEY actual values are.
First thing, it's not a good idea to store the Id in your application and hoping that the Id won't change over time and be consistent. You are right about 'SOURCE_ID' column that it's more consistent compared to the other two (CONTACT_ID is the most brittle while 'RAW_CONTACT_ID' persists at least until user logs out of an account and logs in again).
We had a syncable account with contacts and we used to keep the unique id in one of the general purpose columns in the 'raw_contacts' table (SYNC1 - SYNC10). So although Google suggests that account providers use the database columns in a certain manner but it's upto the provider totally.
General rule to follow is, never use those id's for long term persistence and if you do so, expect them to change. Also since you are making a contact App, you obviously need some kind of reference key. In such case, don't go by the rule that all account providers will put their key in the same column. It's brittle but that's the way it is.
Edit - You should use ContactsColumns.LOOKUP_KEY (previous answer also cited the same). As per the Google Documentation -
LOOKUP_KEY
Added in API level 5 String LOOKUP_KEY An opaque value that contains
hints on how to find the contact if its row id changed as a result of
a sync or aggregation.
Constant Value: "lookup"
https://developer.android.com/reference/android/provider/ContactsContract.ContactsColumns.html#LOOKUP_KEY
You can fetch the lookup key if you have the contact Id using API's provided. Look here - https://developer.android.com/reference/android/provider/ContactsContract.Contacts.html

Android Contacts: Is it possible to reference a given contact entry using a URN?

Let me try and clarify my intentions.
I'm developing an app that accesses to the Android contacts provider. I have already implemented a mechanism for pulling contacts from the contacts provider and storing the results in an SQLite table. Currently, when I query for the results of a contact's _ID, I can retrieve all the data for that contact, phone numbers, email addresses, etc.
However, in order to specify which of those my app should use on future occasions, I have to store the resulting contact data (e.g. CommonDataKinds.Phone.NUMBER, CommonDataKinds.Phone.TYPE etc) in the SQL table.
This presents a problem if the data in the Android contacts provider has changed. One solution I have considered is to re-query the _ID and store the data that has changed. However, implementing such a solution requires gathering all data for that contact, making it difficult to determine the correct contact data to use.
My question is thus:
Is there a unique record key used in the Android Provider's contact data, in the same way as there is in the Provider's contact entry itself? A phone number or email address equivalent of Contact._ID?
Failing that, does the Android contacts provider store the last modified date and time? I'm hoping that if I can't reference the contact data in the provider, I can at least run a check to see if anything has changed since the contact was selected for use in the app, allowing my app to alert the user that the data has changed.
Yoi may use ContentObserver with the help of a service to monitor for contacts change or update.
for example-
extend contentObserver-
public class Contact_change extends ContentObserver
register contentobserver-
Contact_change changeObserver = new Contact_change();
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,chageobserver);
By using this you can monitor for contact changes and update your database.
So while looking to see what was possible, I've come across some interesting findings by doing a localised record dump to my tablet.
I incorrectly referred to the phone _ID when asking my question. It's there, but it references individual records in any given contact. This might be useful, it might be exactly what I hoped, but it might also be a dead end.
So far, I've retrieved a contact using the Android Contacts Provider, which returns the contact's data including the fields that follow
ContactsContract.Contacts._ID
ContactsContract.Contacts.DISPLAY_NAME
After assigning the _ID to a String and using it in a query, I initially searched for the _ID in the ContactsContract.Data._ID field, which did not work as intended.
That's when I realised I was doing it wrong. I needed to apply the search to ContactsContract.Data.CONTACT_ID, which then retrieved all related data records for my selected contact.
Having corrected the error and re-ran my query, I found a series of records for the CONTACT_ID, each of which had its' own unique _ID (with the exception of photos and binary data, which all had a null reference to _ID instead.
Now the question is: Does this data reference change even if a phone number, email address or IM entry is modified, as opposed to deleted and re-created? I'll probably find out through further testing, but I wanted to ask if anyone had already tried this first.
Ultimately, I am hoping my internal SQL table can store only the CONTACT_ID and the _ID for each entry, relying on callbacks to the Android Provider to pull the relevant values. That way, I can be sure the data displayed in my app is up to date between the app and the stored contact data on the device.
Combined with the change notifier code provided here, I should be able to alert the user to any changes that may require action on their part.
Update:
More investigation reveals that the UID associated with a given contact entry is preserved through entry edits.
The UID is lost obviously on deletion, and in my brief testing, I have not found UID's being recycled. This solves a referential integrity issue for me at least, as that UID won't suddenly reference another record out of nowhere.
The upshot for anyone else wanting to reference individual entries in the Contacts Provider is that it's possible, and you can store only the _ID and still retrieve individual entries in the provider.

difference between RawContacts.CONTENT_URI and ContactsContract.Contacts.CONTENT_URI in android

what is the difference between RawContacts.CONTENT_URI and ContactsContract.Contacts.CONTENT_URI in android?
I am trying to write a service which listens to changes in native address book. So, which one to use?
thanks
Niz
A Contact (as the user perceives it) is an aggregate set of RawContact's
A RawContact being some details associated with a certain account or protocol
The ContactsContract.Contacts.CONTENT_URI is generally the correct one to use as it brings back the correct display name from the entire set of matching RawContacts and can help you join all those accounts that are linked
The RawContacts.CONTENT_URI can be used if you want to match a specific [set of] contact relating to an account/protocol
and then there are various data types / directories to bring back even broader ranges of data.
The question of which one should you use comes down to what data you are watching and if/how you are displaying it, as well as how many rows you are trying to watch. I would say more often than not it's correct to use the ContactsContract.
It also depends how granular you want your 'notifications'. I.e. a content observer callback can give you a URL to show you what changed, but nothing more, which means if you want to only act on the specific row that you know has changed then you're going to have to observe different things than if you just want to know some change has occurred and that it's time to notifyDataSetChanged!

Possibility of a custom Contacts field with a set list of values and Contacts lookup performance

I'm pretty sure it's not viable to do what I'd like to based on some initial research, but I figured it couldn't hurt to ask the community of experts here in case someone knows a way.
I'd like to create a custom field for contacts that the user is able to edit from the main Contacts app; however, the user should only be allowed to select from a list of four specific values. A short list of string values would be ideal, but an int with a min/max range would suffice.
I'm interested in knowing if it's possible either way, but also wondering if it make sense to go this route performance wise. More specifically, would it be better to look up a contact (based on a phone number) each time a call or SMS message is received or better to store my own set of data (consisting of name, numbers, and the custom field) and just syncing contact info in a thread every so often? Or syncing contacts the first time the app is run and then registering for changes using ContentObserver?
Here is a similar question with an answer that explains how to add a custom field to a contact.
Thanks in advance.
I don't see the purpose to have your own set of data against contacts stored in your separate database, as you obviously will run into sync issues. You can use the mimetype and store whatever you want against the contact, in the manner you linked.
Whenever you want to looup contacts you can do that by using your custom mimetype. You get the contact id (from ContactsContract.Data.CONTENT_URI), and then you run another query to get the contact details (from ContactsContract.Contacts.CONTENT_URI). Please note these are different tables.
I'd like to create a custom field for contacts that the user is able to edit from the main Contacts app
I don't see that possible, editable from the main app, when you use your custom mimetypes, and you don't have much options here. The main contact app will display only the fields that are in SDK. You can store details against contacts but they won't show up in the inbuilt edit contact screen.

Categories

Resources