如何监听变化联系数据库数据库

2023-09-11 11:09:48 作者:上分大魔王

我想监听在接触数据库的任何变化。

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

所以,我创造我contentObserver这是一个子类ContentObserver的:

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);

不过,当我使用'EditContactActivity来更改联系人数据库,我的onChange函数不会被调用。

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

推荐答案

我已经部署了您的例子,因为它是,它工作正常。

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);
        this.getApplicationContext().getContentResolver().registerContentObserver (People.CONTENT_URI, true, contentObserver);
    }

    private class MyContentObserver extends ContentObserver {

        public MyContentObserver() {
            super(null);
        }

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

    }

    MyContentObserver contentObserver = new MyContentObserver();

}

所以,你必须做一些别的错误。

So, you must be doing something else wrong.

您使通过游标观察员注册了变化?

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

检查与观察功能deliverSelfNotifications()。 (默认情况下它返回false)

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;
    }

请确保People.CONTENT_URI指的是正确的值(android.provider.Contacts.People)。

Make sure that People.CONTENT_URI is referring to correct value (android.provider.Contacts.People).

另外,我建议你使用处理程序ContentObserver,虽然这不是什么使你的code错在这种情况下。

Also, I would suggest you using Handler with ContentObserver, though that is not what makes your code wrong in this case.