Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to listen for changes in Contact Database

Tags:

android

I am trying to listen for any change in the contact database.

So I create my contentObserver which is a child class of ContentObserver:

 private class MyContentObserver extends ContentObserver {

        public MyContentObserver() {
            super(null);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            System.out.println (" Calling onChange" );
        }

    }

MyContentObserver contentObserver = new MyContentObserver();
context.getContentResolver().registerContentObserver (People.CONTENT_URI, true, contentObserver);

But When I use 'EditContactActivity' to change the contact database, My onChange() does not get called.

like image 867
hap497 Avatar asked Sep 09 '09 18:09

hap497


2 Answers

I have deployed your example as it is and it works fine.

package com.test.contentobserver;

import android.app.Activity;
import android.database.ContentObserver;
import android.os.Bundle;
import android.provider.Contacts.People;

public class TestContentObserver extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MyContentObserver contentObserver = new MyContentObserver();
        getApplicationContext().getContentResolver().registerContentObserver(
            ContactsContract.Contacts.CONTENT_URI, 
            true, 
            contentObserver);
    }

    private class MyContentObserver extends ContentObserver {
        public MyContentObserver() {
            super(null);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Log.d(this.class.getSimpleName(), "A change has happened");
        }
    }
}

Something else must be wrong...

Are you making the changes through the cursor the observer is registered with?

Check that with the Observer function deliverSelfNotifications(). (it returns false by default)

You may want to override that observer function with something like:

@Override
public boolean deliverSelfNotifications() {
    return true;
}
like image 171
MannyNS Avatar answered Oct 05 '22 07:10

MannyNS


EDIT: MannyNS's answer has now been updated with the new URI (ContactsContract.Contacts.CONTENT_URI)

A simple TIP about MannyNS 's answer.

Here, People.CONTENT_URI is deprecated.

Code as follows instead.-->ContactsContract.Contacts.CONTENT_URI

    getApplicationContext().getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contentobserver);
like image 21
Nizam Avatar answered Oct 05 '22 07:10

Nizam