Android their definitions ContentProvider and Contentobserver make full use of

Source: Internet
Author: User

When they are used together in their definition contentprovider combined with contentobserver, they write their own contentprovider, after the insert, delete, and update are finished running, To manually call Getcontentresolver (). Notifychange () This method to notify the creation of the modification.

Directly on the code:

Mainactivity

Package Com.jackie.contentobserver;import Java.util.arraylist;import Android.net.uri;import android.os.Bundle; Import Android.os.handler;import android.os.message;import android.app.activity;import android.app.AlertDialog; Import Android.app.alertdialog.builder;import Android.content.contentresolver;import Android.content.ContentUris; Import Android.content.contentvalues;import Android.database.cursor;import Android.util.log;import Android.view.layoutinflater;import Android.view.menu;import Android.view.menuitem;import Android.view.View;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.listview;import Android.widget.textview;public class Mainactivity extends Activity {private arraylist<person> mlist;private ListView mlistview;private contentresolver resolver;private mybaseadapter mbaseadapter;private Handler MHandler; Private Adaptercontentobserver madaptercontentobserver; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (SAvedinstancestate); Setcontentview (r.layout.activity_main); Mlistview = (ListView) Findviewbyid (R.id.lv_person); InitData (); mbaseadapter = new Mybaseadapter (this, mlist); Mlistview.setadapter (mbaseadapter); mhandler = new Handler (); Madaptercontentobserver = new Adaptercontentobserver (this, mhandler); Resolver.registercontentobserver (Uri.parse (" Content://com.jackie.provider.person/person "), true, madaptercontentobserver);//register SMS Change monitor// This.getcontentresolver (). Registercontentobserver (Uri.parse ("content://sms/"), True, content)} @Overrideprotected void OnDestroy () {resolver.unregistercontentobserver (madaptercontentobserver); Super.ondestroy ();} Private Arraylist<person> InitData () {mlist = new arraylist<person> (); resolver = Getcontentresolver (); cursor cursor = resolver.query (Uri.parse ("Content://com.jackie.provider.person/person"), NULL, NULL, NULL, NULL); while (Cursor.movetonext ()) {Person person = new person ();p erson.set_id (Cursor.getint (Cursor.getcolumnindex ("_id")) ;p Erson.setname (cUrsor.getstring (Cursor.getcolumnindex ("name"))); Mlist.add (person);} return mlist;} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.activity_main, menu); return true;} @Overridepublic boolean onmenuitemselected (int featureid, MenuItem item) {switch (Item.getitemid ()) {case R.id.menu_ Settings://alertdialog.builder Builder = new Alertdialog.builder (this);//builder.settitle ("hint"). Setmessage ("Are you sure you want to exit ?");/ /builder.create (). Show (); Contentvalues values = new Contentvalues (); Values.put ("Name", "Jackie");        Uri MUri = Resolver.insert (Uri.parse ("Content://com.jackie.provider.person/person"), values);//Method One: Again query database real-time refresh// Mbaseadapter = new Mybaseadapter (this, InitData ());//Mlistview.setadapter (Mbaseadapter);//Method Two: When the adapter bound list changes, Call adapter's Notifydatasetchanged method for real-time refresh (without querying the database repeatedly, more efficiently)//long id = Contenturis.parseid (mUri);//mlist.add (New person ID, "Chengjie"));//mbaseadapter.notIfydatasetchanged ();//Method Three: Content observers contentobserver//their own contentprovider, after the insert, delete, and update are finished running, To manually call Getcontentresolver (). Notifychange () This method to notify the creation of the modification (please refer to Myprovider.java method) Break;default:break;} Return super.onmenuitemselected (Featureid, item);}}

Adaptercontentobserver.java

Package com.jackie.contentobserver;    Import Android.content.ContentResolver;    Import Android.content.Context;    Import Android.database.ContentObserver;    Import Android.database.Cursor;    Import Android.net.Uri;    Import Android.os.Handler;    Import Android.util.Log;    Import Android.widget.Toast;        public class Adaptercontentobserver extends Contentobserver {private context context;        Private Handler Handler;        private static final int person_update = 0;            Public Adaptercontentobserver (Handler Handler) {super (Handler);            TODO auto-generated Constructor stub} public Adaptercontentobserver (context context, Handler Handler) {            Super (handler);            This.context = context;        This.handler = handler; }//When the listening URI has changed.  This method is run @Override public void OnChange (Boolean selfchange, Uri uri) {super.onchange (Selfchange,            URI); Contentresolver resolver =Context.getcontentresolver ();            Gets the latest data cursor cursor = resolver.query (URI, NULL, NULL, NULL, "_id desc-Limit 1");                while (Cursor.movetonext ()) {int _id = Cursor.getint (Cursor.getcolumnindex ("_id"));            Toast.maketext (Context, "database updated, _id:" + _id, Toast.length_short). Show ();        } cursor.close (); }    }

Dbhelper.java

Package Com.jackie.contentobserver;import Android.content.context;import android.database.sqlite.SQLiteDatabase; Import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends Sqliteopenhelper {public DBHelper (context context, String name, Cursorfactory factory,int ve rsion) {Super (context, name, Factory, version);//TODO auto-generated constructor stub} @Overridepublic void OnCreate ( Sqlitedatabase db) {db.execsql ("CREATE table if not exists person (_id Integer primary key autoincrement, name text)");} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {}}

Mybaseadapter.java
Package Com.jackie.contentobserver;import Java.util.arraylist;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.textview;public class Mybaseadapter extends BaseAdapter {private Viewholder holder;private Context context;private arraylist<person> mlist;public mybaseadapter (context context, Arraylist<person> mlist) {this.context = Context;this.mlist = mlist;} @Overridepublic int GetCount () {return mlist.size ();} @Overridepublic Object getItem (int position) {return mlist.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Layoutinflater Minflater = Layoutinflater . from (context), if (Convertview = = null) {holder = new Viewholder (); Convertview = Minflater.inflate (r.layout.listview_ item, NULL); Holder.idtexitview = (TextView) Convertview.findviewbyid (r.id.tV_ID); Holder.nametextview = (TextView) Convertview.findviewbyid (r.id.tv_name); Convertview.settag (holder);} else {holder = (Viewholder) Convertview.gettag ();} Holder.idTexitView.setText (Mlist.get (position). get_id () + ""); Holder.nameTextView.setText (Mlist.get (position). GetName ()); return Convertview;} Class Viewholder {TextView idtexitview; TextView Nametextview;}}

Myprovider.java

Package Com.jackie.contentobserver;import Android.content.contentprovider;import Android.content.ContentUris; Import Android.content.contentvalues;import Android.content.urimatcher;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.net.uri;public class MyProvider extends ContentProvider { Private final static string authorith = "Com.jackie.provider.person";p rivate final static string persons_path = "Person";p  Rivate final static String Person_path = "person/#";p rivate final static int person = 1;private final static int PERSONS =  2;private final static string database_name = "person_db";p rivate final static string table_name = "Person";p rivate final static string table_column_id = "_id";p rivate final static string table_column_name = "NAME";p rivate final static URIMATC Her murimatcher = new Urimatcher (urimatcher.no_match); static {Murimatcher.adduri (Authorith, Persons_path, PERSONS); Murimatcher.adduri (Authorith, Person_path, person);} Private DBHelper Helper = null; @Overridepublic boolean onCreate () {helper = new DBHelper (GetContext (), database_name, NULL, 1); return Tru e;} @Overridepublic Cursor query (Uri uri, string[] projection, string selection,string[] Selectionargs, string sortOrder) {SQ Litedatabase database = helper.getwritabledatabase (); switch (Murimatcher.match (URI)) {case Person:long id = Contenturis.parseid (URI); String where = table_column_id + "=" + id;if (selection! = NULL &&! "). Equals (selection)) {selection = where + "and" + selection;} Return Database.query (table_name, projection, selection, Selectionargs, NULL, NULL, sortOrder); case Persons:return Database.query (table_name, projection, selection, Selectionargs, NULL, NULL, SortOrder);d Efault:throw New IllegalArgumentException ("UnKnown uri:" + uri);}} @Overridepublic String getType (Uri uri) {switch (Murimatcher.match (URI)) {case Person:return "Vnd.android.cursor.item" Case Persons:return "Vnd.android.cursor.dir";d efault:throw new IllegalArgumentException ("UnknOwn URI: "+ uri);}} @Overridepublic uri insert (URI uri, contentvalues values) {sqlitedatabase database = Helper.getwritabledatabase (); long                ID = database.insert (table_name, table_column_name, values);//notify the outside world that the data in the ContentProvider has changed so that the Contentobserver makes the corresponding GetContext (). Getcontentresolver (). Notifychange (URI, null); return Contenturis.withappendedid (URI, id);} @Overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {sqlitedatabase database = Helper.getwritab Ledatabase (); switch (Murimatcher.match (URI)) {case Person:long id = contenturis.parseid (URI); String where = table_column_id + "=" + id;if (selection! = NULL &&! "). Equals (selection)) {selection = where + "and" + selection;} Return Database.delete (table_name, selection, Selectionargs); case Persons:return Database.delete (table_name, Selection, Selectionargs);d efault:throw new IllegalArgumentException ("UnKnown uri:" + uri);}} @Overridepublic int update (URI uri, contentvalues values, String selectioN,string[] Selectionargs) {//TODO auto-generated method Stubreturn 0;}} 

Person.java

Package Com.jackie.contentobserver;public class Person {private long _id;private String name;public person (long _id, stri ng name) {super (); this._id = _id;this.name = name;} Public person () {super ();//TODO auto-generated constructor Stub}public long get_id () {return _id;} public void set_id (long _id) {this._id = _id;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Android their definitions ContentProvider and Contentobserver make full use of

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.