If ContentProvider visitors need to know the changes in the data in ContentProvider, they can call Getcontentresolver () when the data changes ContentProvider. Notifychange (Uri,null) to notify visitors registering on this URI.
Copy Code code as follows:
public class Personcontentprovider extends contentprovider[
Public URI Insert (Uri uri,contentvalues values) {
Db.insert ("Person", "PersonID", values);
GetContext (). Getcontentresolver ().
Notifychange (Uri,null);
}//notify visitors registered on this URI, in addition to registering on the Insert method}
If a contentprovider visitor needs to be notified of changes to the data, you must use Contentobserver to monitor the data (data using a URI description), and when you hear data change notifications, The system invokes the Contentobserver onchange () method.
Copy Code code as follows:
public class Mainactivity extends activity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Uri uri = uri.parse ("Content://cn.wordtech.providers.personprovider/person");
This. Getcontentresolver (). Registercontentobserver (URI, True, new personcontentdobserver(New Handler ()));
The third object is the listener and notifies the object when the data changes to make a corresponding change
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
Private class Personcontentdobserver extends contentobserver {
Public Personcontentdobserver (Handler Handler) {
Super (handler);
}
@Override
public void OnChange(Boolean selfchange) {
Uri uri = uri.parse ("Content://cn.wordtech.providers.personprovider/person");
Cursor Cursor = Getcontentresolver (). Query (URI, NULL, NULL, NULL, "PersonID desc limit 1");
while (Cursor.movetonext ()) {
String name = cursor.getstring (Cursor.getcolumnindex ("name"));
LOG.I ("name", name);
}
Super.onchange (Selfchange);
} }
}
Test Application:
Copy Code code as follows:
Button btn = (button) Findviewbyid (R.ID.BTN);
Btn.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
Uri uri = uri.parse ("Content://cn.wordtech.providers.personprovider/person")//content provider based on identity name
Contentresolver CR = MainActivity.this.getContentResolver ();
Contentvalues values = new Contentvalues ();
Values.put ("name", "Livingstone");
Values.put ("Phone", "1101");
Values.put ("Amount", "1111111111");
Cr.insert (URI, values);
}
});