How do I make my Android ContentObserver for ContactsContract detect a added, updated or deleted contact?

contentobserver in service android
contact observer android

I am able to get a generic notification "that there was a change to the contacts DB", but I want to know the specific record that was inserted, updated, or deleted. Following is the code that gets registered and gets the onChange notification. Unfortunately, it is not specific which makes my processing exhaustive and inefficient.

Here is the code stub:

            if ((mNativeContactsObserver == null) && (mHandler == null)) {
            mHandler = new Handler(this.getMainLooper()) {
            };
            mNativeContactsObserver = new ContentObserver(mHandler) {
                @Override
                public void onChange(boolean selfChange) {
                    super.onChange(selfChange);

                    Bundle data = null;
                    Message message = mHandler.obtainMessage();
                    if (message != null) {
                        data = message.getData();
                        if (data != null) {
                            Logs.d(TAG, "Message = [" + message.toString() + "] data=[" + data.toString() + "]");
                            Logs.d(TAG, "Contents = [" + message.describeContents() + "]");
                        }
                    }

                    if (!selfChange) {
                        final Account accountListen = MySyncAdapter.lookupAccount(TAG, getApplicationContext(), getUserProfile().getAccountId(), AUTHORITY_MY_SYNC);
                        Logs.d(TAG, "onChange!? account: " + accountListen.name);
                        if (!ContentResolver.isSyncPending(account, ContactsContract.AUTHORITY) 
                                && (!ContentResolver.isSyncActive(account, ContactsContract.AUTHORITY))) {
                            Bundle extras = new Bundle();
                            extras.putInt(MySyncAdapter.EXTRA_SYNC_TYPE, MySyncAdapter.REQUEST_SYNC_NATIVE_CHANGED);
                            ContentResolver.requestSync(accountListen, ContactsContract.AUTHORITY, extras);
                        } else {
                            Logs.w(TAG, "There is a pending sync.  This request is ignored.");
                        }
                    }
                }
            };
        }
        Uri uriContactsListen = ContactsContract.Contacts.CONTENT_URI.buildUpon().appendEncodedPath("#").build();
        Logs.i(TAG, "Register listening for native contacts changes. [" + uriContactsListen + "]");
        cr.registerContentObserver(uriContactsListen, true, mNativeContactsObserver);

Finally at least i am able to detect is this Update/Delete/Insert look at my OnChange method as below

 @Override
       public void onChange(boolean selfChange) {
           super.onChange(selfChange);
           Log.e("ContactChangeObserver", "onChange");

           // 0 Update , 1 Delete , 2 Added
 // Get count from phone contacts
           final int currentCount = contactDBOperaion.getContactsCountFromPhone();

 // Get count from your sqlite database
           int mContactCount= DbContacts.getInstance().getContactsCount();

           if (currentCount < mContactCount) {
               // DELETE HAPPEN.
               Log.e("Status", "Deletion");
               contactDBOperaion.SyncContacts(1);
           } else if (currentCount == mContactCount) {
               // UPDATE HAPPEN.
               contactDBOperaion.SyncContacts(0);
           } else {
               // INSERT HAPPEN.
               Log.e("Status", "Insertion");
               contactDBOperaion.SyncContacts(2);
           }
       }

When Update occurred i update all contacts

When Insert occurred i am inserting newly added row , after checking isExist in existing database

When Delete occurred not found solution yet

ContactsContract.RawContacts, I am able to get a generic notification. How do I make my Android ContentObserver for ContactsContract detect a added, updated or deleted contact? Question. Android : Detect new Contact addition October 29, 2017 Tags Adapter Android API Campaign Tracking CardView ContentObserver ExoPlayer FCM Firebase Google Location Service GPS Hybrid App Install Referrer kafka Kotlin New Contact Node.js Project Structure Push Notification python React Native RecyclerView Volley


I have this code in my Application base class.

private ContentObserver contactObserver = new ContactObserver();

private class ContactObserver extends ContentObserver {

    public ContactObserver() {
        super(null);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

        // Since onChange do not sent which user have been changed, you 
        // have to figure out how to match it with your data.
        // Note: Contact is  one of my classes.
        for (Contact contact : getContacts()) {
            if (!contact.isLinked())
                continue;

            String selection = ContactsContract.Data._ID + " = ?";
            String[] selectionArgs = new String[] { contact.getSystemId() };
            String[] projection = new String[] { ContactsContract.Data.DISPLAY_NAME };
            Cursor cursor = getContentResolver().query(
                    ContactsContract.Contacts.CONTENT_URI, projection,
                    selection, selectionArgs, null);

            if (!cursor.moveToFirst())
                return;

            String name = cursor.getString(0);

            if (contact.getUsername().equalsIgnoreCase(name))
                continue;

            contact.setUserName(name);

        }
    }
}

Regarding about what you can put in projection check here

Unfortunately, it is not specific which makes my processing exhaustive and inefficient.

Would be great if into next Android releases also will send the contact id which had been just changed.

Hope this helps

How to listen contact inserted/updated/deleted in - android, Added in API level 5 When a raw contact is deleted, all of its Data rows as well as StatusUpdates, AggregationExceptions, To find raw contacts within a specific account, you can either put the account name and type in the Aggregation mode: aggregate immediately after insert or update operation(s) are complete. 31 How do I make my Android ContentObserver for ContactsContract detect a added, updated or deleted contact? 29 When is it necessary to use singleTop launchMode in an android widget or application? View more network posts →


First of all, you have to register your contentObserver to receive change notification.

Do this by calling :

registerContentObserver();

Here's the specs : registerContetObserver

After than you'll want to notify all the listeners when a modification happens :

contentResolver.notifyChange();

Here's the specs for that one : notifyChange

Hope it helps ;)

Cheers !

Use Android's ContentObserver in Your Code to Listen to Data , Tried using ContentObserver but onChange() is getting called multiple times. It's difficult to find the contact changes data. public class ContactService extends just count the number of contacts since one might have been deleted and one added NOTES,"My test Notes"); getContentResolver().update(​ContactsContract. When you are using a content provider as a client, chances are that you want to know whenever the data changes. That's what Android's class ContentObserver is for. To use the ContentObserver you have to take two steps: Implement a subclass of ContentObserver Register your content observer to listen for changes Implement a subclass of [] Continue Reading "Use Android’s ContentObserver in


Use Loaders to query and display the list of contacts on your android device on your emulator. They automatically detect changes in the underlying data and reflect that on your UI.

How+do+I+make+my+Android+ContentObserver+for+ , To use the ContentObserver you have to take two steps: Since Google added one of the two overloaded onChange() methods this method's default behavior is to call the other, older method. This can be handy for say the ContactsContract URI with its many Like if a record was deleted or inserted. The example code work. But the getAllContacts() method just print added or exist contacts info in the logcat console. You had better add below code to require WRITE_CONTACTS permission before add contacts.


core/java/android/provider/ContactsContract.java, ContactsContract defines an extensible database of contact-related An optional URI parameter for insert, update, or delete queries Add this query parameter to a URI to get back row counts grouped by the inserted, the provider will first try to find a Contact representing the Constants for the deleted contact table. The following are top voted examples for showing how to use android.database.ContentObserver.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.


🧖 ‍ How can I check CanCan in console?, object_to_be_checked: - the object on which you want to check authorization Android ContentObserver for ContactsContract detect an added, updated or deleted contact? You want to find human nodes based on the value of several attributes. If you are trying to get the values ​​of the specified attributes, I would  How do I make my Android ContentObserver for ContactsContract detect a added, updated or deleted contact? Tags ajax android angular api button c++ class database date dynamic exception file function html http image input java javascript jquery json laravel list mysql object oop ph php phplaravel phpmysql phpphp post python sed select spring sql


ContentObserver - Android - Java, The Observer Pattern is a software design pattern that establishes a This can be handy for say the ContactsContract URI with its many descendants. you start coding registerABC() immediately also add the code to unregisterABC(). like if contact will be created, deleted or modified all cases, we will get notification in  Q&A for SharePoint enthusiasts. Stack Exchange network consists of 177 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.