sangram
sangram

Reputation: 141

how to know if a contact is added, changed or deleted in android

I am working on an application whereby I need to listen to changes in native contacts database like if a contact is edited/deleted or a new contact is added.

I know I can achieve this with the help of contentobservers. However I found it pretty strange that android SDK does not provide a way to know which contact is added/deleted or which one is changed. This results in a lot of manual work like traversing through entire contact list and checking which one is changed.

I want to know if there is any better way of achieving this. I know this question would have been asked many times but I want to know why Android SDK does not have such a mechanism in place?

Thanks.

Upvotes: 3

Views: 1729

Answers (2)

Bivin
Bivin

Reputation: 1

This service class provide the wake up call from the changes of contacts add, update, delete operations from the background. I don't know whether this piece of code is useful for you.

public class ContactOberverService extends Service {
    private static final String TAG = "ContactOberverService";


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public class MyContactContentObserver extends ContentObserver {
        public MyContactContentObserver() {
            super(null);
            Log.d(":-> Service Called","in construcrtor ");
        }
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Log.d(":-> Service Called","In onChange");
            ContactsDbOprations.getAllContacts();
        }

        @Override
        public boolean deliverSelfNotifications() {
            return true;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI,
                true, new MyContactContentObserver());
    }
}

Upvotes: 0

cybersam
cybersam

Reputation: 66977

This interesting thread from the early days of Android indicates that the ContentObserver did use to tell you what had changed, but it was too difficult to provide that information. It goes on to state why (at least at that time) re-querying was thought to be good enough and safer.

Upvotes: 2

Related Questions