About using URIs in Android to listen for changes in the database

Source: Internet
Author: User

Online original on the monitoring database changes in the article very few, basically did not find a useful one, so I went to see the source of Bluetooth transmission, wrote a demo, put here for everyone to reference, see Source:


SRC contains three files Mydataprovider, mainactivity and Mybean, see below:

Mydataprovider.java:

public class Mydataprovider extends contentprovider{//public static final String SCHEME = "Test"; public static final String SCHEME = "content";    The code inside the provisions of this write, so this place can not change public static final String HOST = "Com.zyj";    public static final String PORT = "497393102";    public static final String PATH = "simple";    public static final int ALARMS = 1;    public static final String Share_list_type = "com.zyj.test.dir/";    public static final int alarms_id = 2;    public static final String Share_type = "com.zyj.test.item/";    private static final Urimatcher Surimatcher = new Urimatcher (urimatcher.no_match);    Private Sqliteopenhelper MDB = null; ===content://com.zyj:497393102/simple public static final Uri Content_uri = uri.parse (SCHEME + "://" + HOST + ":" +    PORT + "/" + PATH); To add a URI matching method, return is the above custom integer type, 1 for operation is a batch, 2 operation is a separate object static {Surimatcher.adduri (HOST + ":" + PORT, PATH, a        Larms); Surimatcher.adduri (HOST + ":" + PORT, PATH + "/#", ALARMS_ID); } @Override public Boolean onCreate () {mdb = new MyDB (GetContext ());//Get a reference to the database return MDB! = nul    L } @Override public String getType (URI uri) {//Get the type of our custom URI, see above your own definition int match = surimatcher.ma        TCH (URI);            Switch (match) {case ALARMS: {return share_list_type;            } case alarms_id: {return share_type;            } default: {Throw new IllegalArgumentException ("Unknown uri:" + uri); }}} @Override public uri insert (URI uri, contentvalues values) {///first is to see if the URI and our custom match, and match the data        Attributes are inserted into the database and comrades update Sqlitedatabase db = Mdb.getwritabledatabase (); if (Surimatcher.match (URI) = ALARMS) {throw new IllegalArgumentException ("Unknown/invalid uri" + uri)        ;        } contentvalues filteredvalues = new Contentvalues (); FiltEredvalues.put (mydb.bean_id, Values.getasinteger (mydb.bean_id));        Filteredvalues.put (Mydb.message, values.getasstring (mydb.message));        Filteredvalues.put (Mydb.task_progress, Values.getasfloat (mydb.task_progress));        Long RowID = Db.insert (Mydb.tablet, NULL, filteredvalues);        if (RowID! =-1) {GetContext (). Getcontentresolver (). Notifychange (URI, NULL);    } return Content_uri; } @Override public int delete (URI Uri, String selection, string[] Selectionargs) {///first to see if the URI matches our custom,        The match is deleted sqlitedatabase db = Mdb.getwritabledatabase ();        int count = 0;        int match = Surimatcher.match (URI);                Switch (match) {case Alarms:case alarms_id:string where = null; This matches the selection to see if you are passing a batch or a separate file if (selection! = null) {i F (match = = ALARMS) {wheRe = "(" + Selection + ")";                    } else {where = "(" + Selection + ") and";                }} else {where = ""; } if (match = = alarms_id) {//If you are passing a separate file, that is, adding/item after the URI, then this value is associated with the                    The attribute segments in the database are compared, returning the where String segment = Uri.getpathsegments () in the SQL statement. Get (1);                    Long rowId = Long.parselong (segment);                where + = "(" + mydb.bean_id + "=" + RowId + ")";                } count = Db.delete (Mydb.tablet, where, Selectionargs);            Break        Default:throw New Unsupportedoperationexception ("Cannot delete uri:" + uri);        } getcontext (). Getcontentresolver (). Notifychange (URI, NULL);    return count; } @Override public int update (URI uri, Contentvalues valuES, String selection, string[] Selectionargs) {//basic ibid. sqlitedatabase db = Mdb.getwritabledatabase ();        int count;        Long rowId = 0;        int match = Surimatcher.match (URI);                Switch (match) {case Alarms:case alarms_id: {String mywhere;                        if (selection! = null) {if (match = = ALARMS) {                    Mywhere = "(" + Selection + ")";                    } else {mywhere = "(" + Selection + ") and";                }} else {mywhere = ""; } if (match = = alarms_id) {String segment = Uri.getpathsegments (). Get (1)                    ;                    RowId = Long.parselong (segment); Mywhere + = "(" + mydb.bean_id + "=" + rowId+ " ) "; } if (Values.size () > 0) {count = Db.update (Mydb.tablet, values, MYWH                Ere, Selectionargs);                } else {count = 0;            } break;            } default: {Throw new Unsupportedoperationexception ("Cannot update URI:" + uri);        }} getcontext (). Getcontentresolver (). Notifychange (URI, NULL);    return count; @Override public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, String Sorto        Rder) {Sqlitedatabase db = Mdb.getreadabledatabase (); Sqlitequerybuilder QB = new Sqlitequerybuilder ();        Sqlitequerybuilder is an auxiliary class that constructs a SQL query statement, int match = Surimatcher.match (URI);                Switch (match) {case ALARMS: {qb.settables (Mydb.tablet);            Break} case alarms_id: {qb.settables (Mydb.tablet);                Qb.appendwhere (mydb.bean_id + "=");                Qb.appendwhere (Uri.getpathsegments (). Get (1));            Break        } Default:throw New IllegalArgumentException ("Unknown uri:" + uri);        } Cursor ret = qb.query (db, Projection, selection, Selectionargs, NULL, NULL, sortOrder);            if (ret! = null) {Ret.setnotificationuri (GetContext (). Getcontentresolver (), URI);        LOG.D ("Zyj", "created cursor" + RET + "on behalf of");        } else {log.d ("Zyj", "Query failed in downloads database");    } return ret; } private static Class MyDB extends Sqliteopenhelper {//This is the database, database fields, names, table names, etc.. private static FINA        L String DATABASE = "Test_database";        public static final String TABLET = "test_table";        public static String ID = "_id"; Publicstatic String bean_id = "_bean_id";        public static String MESSAGE = "_message";        public static String task_progress = "_progress";        Private sqlitedatabase MDB = null; Private final String mSQL = "CREATE TABLE IF not EXISTS" + TABLET + "(" + ID + "INTEGER PRIMARY KEY AUTO        INCREMENT, "+ bean_id +" text, "+ MESSAGE +" text, "+ task_progress +" text) ";        Private MyDB (Context context) {Super (context, DATABASE, NULL, 1);            } @Override public void OnCreate (Sqlitedatabase db) {MDB = db;        Mdb.execsql (mSQL); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {// Upgrade, you can go to implement}}}

Mybean.java an Instance Object

public class mybean{public    int id = 0;        Public String message = NULL;    public float progress = 0.0f;    public Mybean (int id)    {        this.id = ID;    }    }


Mainactivity.java the main interface.

public class Mainactivity extends activity{TextView mmessage = null;    Private Contentobserver mdatabaselistener = null;    Private Handler Mhand = null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mmessage = (TextView) Findviewbyid (r.id.message);        Init (); Register the database for listening, corresponding to the specific URI getcontentresolver (). Registercontentobserver (Mydataprovider.content_uri, True, Mdatabaselis    Tener);        } @Override protected void OnDestroy () {Super.ondestroy ();    Log off the monitor  getcontentresolver (). Unregistercontentobserver (Mdatabaselistener);        } private void Init () {Mhand = new Handler (); Callback for database Change  mdatabaselistener = new Contentobserver (mhand) {@Override public bo Olean deliverselfnotifications () {System.out.println ("deliverselfnotifications ---------------- ");            return Super.deliverselfnotifications (); } @Override public void OnChange (Boolean selfchange, Uri uri) {System.out                . println ("OnChange----------------" + uri.tostring ());            Super.onchange (Selfchange, URI); } @Override public void OnChange (Boolean selfchange) {System.out.println (                "OnChange----------------...");            Super.onchange (Selfchange);    }        };    } private int count = 0; public void Onviewclick (view view) {switch (View.getid ()) {case R.id.add://                Insert Data  contentvalues calues = new Contentvalues ();                Calues.put ("_bean_id", count++);                Calues.put ("_message", "aaaaaaaaaaaaaaaaaaaaa");                Calues.put ("_progress", 0.0f); Getcontentresolver (). Insert (Mydataprovider.content_urI, calues);            Break Case R.id.del://If the specified _bean_id=1, 2, 3 are not found, the database does not increment or decrement, but the callback method Getcontentresolver () is called. Delete (U                Ri.parse (MyDataProvider.CONTENT_URI.toString () + "/1"), NULL, NULL);                Getcontentresolver (). Delete (Uri.parse (MyDataProvider.CONTENT_URI.toString () + "/2"), NULL, NULL);                Getcontentresolver (). Delete (Uri.parse (MyDataProvider.CONTENT_URI.toString () + "/3"), NULL, NULL);            Break                Case R.id.modify:contentvalues values = new Contentvalues ();                Values.put ("_message", "zzzzzzzzzzzzzzzzzzzzz"); The two methods are the same, so that you can more understand the Uri in the/item added after the meaning of the number Getcontentresolver (). Update (Uri.parse (My                DataProvider.CONTENT_URI.toString () + "/5"), values, NULL, NULL);                Getcontentresolver (). Update (Mydataprovider.content_uri, values, "_bean_id=?", new string[] {"6"});            Break Case R.id.quEry:showmessage (Getcontentresolver (). query (Mydataprovider.content_uri, NULL, NULL, NULL, NULL));        Break        }} private void ShowMessage (Cursor c) {if (c = = null) {return;        } final StringBuffer sb = new StringBuffer (); if (C.getcount () > 0) {while (C.movetonext ()) {Mybean bean = new Mybean (c                . GetInt (C.getcolumnindex ("_bean_id")));                Bean.message = c.getstring (C.getcolumnindex ("_message"));                bean.progress = C.getfloat (C.getcolumnindex ("_progress"));            Sb.append (Bean.id + "\t\t\t:" + bean.message + "\t\t\t,progress =" + bean.progress + "\ n");        }} c.close (); Mhand.post (New Runnable () {public void run () {Mmessage.settext (sb.tostring ()            );    }        }); }}

Activity_main.xml above is four buttons, here is a textview display control
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" android:padding= "10.0dip" > <linearlayout android:layout_width= "Fill_parent" a            ndroid:layout_height= "0dip" android:layout_weight= "1" android:orientation= "vertical" > <button Android:id= "@+id/add" android:layout_width= "fill_parent" android:layout_height= "Wrap_cont Ent "android:onclick=" Onviewclick "android:text=" Add "/> <button android:id= "@+id/del" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Androi            d:onclick= "Onviewclick" android:text= "Delete"/> <button android:id= "@+id/modify"       Android:layout_width= "Fill_parent"     android:layout_height= "Wrap_content" android:onclick= "Onviewclick" android:text= "Modify"/> <button android:id= "@+id/query" android:layout_width= "Fill_parent" Android:layo ut_height= "Wrap_content" android:onclick= "Onviewclick" android:text= "Query"/> </linearlayo ut> <scrollview android:layout_width= "fill_parent" android:layout_height= "0dip" Android:layo ut_weight= "1" android:maxheight= "20dip" > <textview android:id= "@+id/message" an    Droid:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:textsize= "20sp"/> </ScrollView></LinearLayout>


The last is Androidmanifest.xml, and the same as usual, but in the inside will be your own definition of ContentProvider written, similar to my:

<provider
Android:name= "Com.example.databasetest.MyDataProvider"
android:authorities= "com.zyj:497393102"/>
The above authorities attribute is must write, it is above the mydataprovider.java inside of the Content_uri host + ":" + PORT, you can see the following pictures, it is more clear.


Content://com.example.project:200/folder/subfolder/etc
\---------/  \---------------------------/ \---/ \--------------------------/
Scheme Host Port Path
\--------------------------------/
Authority



Then there is no, you can run your own, feel the URI and database monitoring.


There are mistakes in the hope to come out, thank you!!!

Listening to database changes using URIs in Android

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.