Question

I'm trying to extract the Contacts when the contact table is changed. It was working fine but now doesn't work. It only works a few times. I'm using ContentObserver to get the event.

Here's the code to register the ContentObserver. I'm registering it on a Service to be constantly listening.

public void onCreate() {
    super.onCreate();
    context = this;
    db = new Database(context);
    Log.i("**********", "Started Service!");

    Contacts contacts = new Contacts(context);
     context.getContentResolver().registerContentObserver (ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, contacts);

}

And here's the code when I extract the contacts name and this stuf:

public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    Log.i("********","*****");
    db = new Database(co);
    db.open();
    if (db.Preferences(3) && new CheckConexion().isOnline(co)) {
        Cursor phones = co.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                null, null, null);

        while (phones.moveToNext()) {
            try {
                name = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                phoneNumber = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                JSONObject jobject = db.select_contact(name, phoneNumber);

                String type1 = jobject.getString("type");

                if (type1.equals("upload")) {
                    if (!(name.equals("") && phoneNumber.equals(""))) {
                        JSONObject jobject2 = new JSONObject();
                        jobject2.put("name", name);
                        jobject2.put("phone", phoneNumber);

                        String value_json = String.valueOf(jobject2);
                        upload(value_json, co);
                        Log.i("********", "Upload on the db" + name + "  "
                                + phoneNumber);
                    }

                } else {
                    return;
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        db.close();
    } else {
        db.close();
    }

}
Was it helpful?

Solution

Oncreate() is called only once for a service when it is started for the first time. If you are starting the service again and again then onStartCommand() will be called directly. Therefore I feel its the observer registration is not being retained and is getting lost.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top