ContentProvider content provider: Allow other apps to access private databases (files)
1.androidmanifest.xml
Configure Provider
<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.dbtest"Android:versioncode= "1"Android:versionname= "1.0" > <USES-SDKandroid:minsdkversion= "8"android:targetsdkversion= "+" /> <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >
<!--android:name= "Com.example.dbtest.PersonContentProvider" Must be a path to the content provider class or it will be reported notfoundclass--><providerAndroid:name= "Com.example.dbtest.PersonContentProvider"android:authorities= "Com.example.dbtest.provider.personprovider"android:exported= "true"></provider> <ActivityAndroid:name=". Mainactivity "Android:label= "@string/app_name" > <Intent-filter> <ActionAndroid:name= "Android.intent.action.MAIN" /> <categoryAndroid:name= "Android.intent.category.LAUNCHER" /> </Intent-filter> </Activity> </Application></Manifest>
2.PersonContentProvider
Packagecom.example.dbtest;ImportCom.example.dbtest.dbHelper.DbOpenHelper;ImportAndroid.content.ContentProvider;Importandroid.content.ContentValues;ImportAndroid.content.UriMatcher;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.net.Uri; Public classPersoncontentproviderextendsContentProvider {PrivateDbopenhelper Helper; //defines a URI to match the URI if the path does not meet the criteria returned-1 Private StaticUrimatcher Matcher =NewUrimatcher (Urimatcher.no_match); Private Static Final intINSERT = 1; Private Static Final intDELETE = 2; Private Static Final intUPDATE = 3; Private Static Final intQUERY = 4; Static{Matcher.adduri ("Com.example.dbtest.provider.personprovider", "Insert", INSERT); Matcher.adduri ("Com.example.dbtest.provider.personprovider", "delete", DELETE); Matcher.adduri ("Com.example.dbtest.provider.personprovider", "Update", UPDATE); Matcher.adduri ("Com.example.dbtest.provider.personprovider", "Query", QUERY); } //content://Com.itheima.db.personprovider/insert Add Action//content://Com.itheima.db.personprovider/delete Delete Operation//content://com.itheima.db.personprovider/update Update Operations//content://com.itheima.db.personprovider/query Query Operations@Override Public BooleanonCreate () {helper=NewDbopenhelper (GetContext ()); return true; } @Override PublicCursor query (Uri uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) { if(Matcher.match (uri) = =QUERY) {Sqlitedatabase db=helper.getwritabledatabase (); Cursor Cursor= Db.query ("person", projection, selection, Selectionargs,NULL,NULL, SortOrder); //Note When using ContentProvider, do not turn off the data or get the data//db.close (); Do not close returncursor; } Else { Throw NewIllegalArgumentException ("Path not paired, cannot perform query operation"); }} @Override PublicString getType (Uri uri) {return NULL; } @Override Publicuri insert (URI uri, contentvalues values) {if(Matcher.match (uri) = =INSERT) {Sqlitedatabase db=helper.getwritabledatabase (); Db.insert ("Person",NULL, values); } Else { Throw NewIllegalArgumentException ("Path not paired, cannot perform insert operation"); } return NULL; } @Override Public intDelete (Uri Uri, String selection, string[] selectionargs) {if(Matcher.match (uri) = =DELETE) {Sqlitedatabase db=helper.getwritabledatabase (); Db.delete ("Person", Selection, Selectionargs); } Else { Throw NewIllegalArgumentException ("Path is not paired, delete operation cannot be performed"); } return0; } @Override Public intupdate (URI Uri, contentvalues values, String selection, string[] selectionargs) {if(Matcher.match (uri) = =UPDATE) {Sqlitedatabase db=helper.getwritabledatabase (); Db.update ("Person", values, selection, Selectionargs); } Else { Throw NewIllegalArgumentException ("Path not paired, cannot perform modify operation"); } return0; }}
3. Other app call content providers
PackageCom.example.getcontentprovider;ImportAndroid.content.ContentResolver;Importandroid.content.ContentValues;ImportAndroid.database.Cursor;ImportAndroid.net.Uri;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.widget.Toast; Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); } Public voidquery (view view) {System.out.println ("Start query ........."); Contentresolver Resolver=Getcontentresolver (); Uri URI= Uri.parse ("Content://com.example.dbtest.provider.personprovider/query"); Cursor Cursor= Resolver.query (URI,NULL,NULL,NULL,NULL); StringBuffer SB=NewStringBuffer (); while(Cursor.movetonext ()) {System.out.println ("Name:" +cursor.getstring (Cursor.getcolumnindex ("name"))); Sb.append ("Name:" +cursor.getstring (Cursor.getcolumnindex ("name")) + "\ n"); } System.out.println ("End query ........"); Toast.maketext ( This, sb.tostring (), 0). Show (); } Public voidDelete (view view) {Contentresolver resolver=Getcontentresolver (); Uri URI= Uri.parse ("Content://com.example.dbtest.provider.personprovider/delete"); Resolver.delete (URI,"Id=?",Newstring[]{"1"}); Toast.maketext ( This, "Delete succeeded", 0). Show (); } Public voidUpdate (view view) {Contentresolver resolver=Getcontentresolver (); Uri URI= Uri.parse ("Content://com.example.dbtest.provider.personprovider/update"); Contentvalues Values=Newcontentvalues (); Values.put ("Name", "Zhang San"); Resolver.update (URI, values,"Id=?",Newstring[]{"1"}); Toast.maketext ( This, "modified successfully", 0). Show (); } Public voidInsert (view view) {Contentresolver resolver=Getcontentresolver (); Uri URI= Uri.parse ("Content://com.example.dbtest.provider.personprovider/insert"); Contentvalues Values=Newcontentvalues (); Values.put ("Name", "John Doe"); Resolver.insert (URI, values); Toast.maketext ( This, "modified successfully", 0). Show (); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {intID =Item.getitemid (); if(id = =r.id.action_settings) { return true; } return Super. onoptionsitemselected (item); }}
Android ContentProvider content Provider