ContentProvider Introduction
ContentProvider is a flag API for exchanging data between different applications
That is to say: An application exposes its own data manipulation interface through ContentProvider, so whether or not the application starts (and is deployed), other applications can manipulate the application's internal data through the interface, including adding data, deleting data, and altering data. Query data, and so on.
When an application inherits the ContentProvider class and overrides the method used to provide data and store data, it is able to share its data with other applications.
Although other methods can be used to share data externally, data access can vary depending on how the data is stored
Such as: the use of file-sharing data, the need for file operations read and write data.
Share data with sharedpreferences. You need to read and write data using the Sharedpreferences API.
The advantage of using ContentProvider to share data is to unify the data access method .
To share data steps with ContentProvider: Inherit ContentProvider and override the following methodsPublic class Personcontentprovider extends contentprovider{
public boolean onCreate ()
Public URI insert (URI uri, contentvalues values)
public int Delete (URI Uri, String selection, string[] Selectionargs)
public int update (URI uri, contentvalues values, String selection, string[] Selectionargs)
Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder)
Public String GetType (URI uri)
}
Method Introduction
public boolean onCreate ()
After Usercontentprovider is created, it is called when the other application first visits Contentprivider. The ContentProvider will be created.
Public String GetType (URI uri)
The type of return operation assumes the operation of multiple records then the mine type vnd.android.cursor.dir/begins
Assuming that the operation's data has only one record then mine type vnd.android.cursor.item/start
Public URI insert (URI uri, contentvalues values)
Insert operation
public int Delete (URI Uri, String selection, string[] Selectionargs)
Delete operation
public int update (URI uri, contentvalues values, String selection, string[] Selectionargs)
Change operation
Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder)
Query operations
Use <provider> to configure the ContentProvider in Androidmanifest.xml
In order to allow other applications to find the ContentProvider. ContentProvider uses the authorities (hostname/domain name) to uniquely identify it, you can think of ContentProvider as a site (thinking, the site is also to provide data), authorities is his domain name:
<manifest. >
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<provider android:name= ". Personcontentprovider "android:authorities=" Cn.itcast.provider.personprovider "/>
</application>
</manifest>
Note: Once the app inherits the ContentProvider class, we'll refer to this app as the ContentProvider (content provider) later.
Uri Description URI represents the data to be manipulated
The URI consists mainly of two pieces of information:
- ContentProvider to be operated.
- To manipulate what data in the ContentProvider
URI component
- Scheme:contentprovider (content Provider) scheme has been provided by Android, scheme: content://
- hostname (or authority): used to uniquely identify this contentprovider, an external caller can find it based on this identity.
- Path: can be used to represent the data we want to manipulate. The path should be built according to the business.
- To manipulate records with ID 10 in the person table, you can build this path:/PERSON/10
- To manipulate the name field of the record with ID 10 in the person table, Person/10/name
- To manipulate all the records in the person table, you can build this path:/person
- You want to manipulate the records in the XXX table. Ability to build this path:/xxx
- Of course the data to be manipulated does not necessarily come from the database. It can also be a file, XML, or network, such as the following:
- You want to manipulate the name node under the person node in the XML file. Ability to build this path:/person/name
When other applications want to access this project, they need an access address, which is the same role as the URL we visit. For example, the following:
Url:http://www.baidu.com/index.htmlhttp:HTTP protocol interview siteWww.baidu.comDomain Name Section/index.html:Site Resource URI:Content://www.csdn.com.provider.usercontentprovider/usercontent://Android's ContentProvider rules
Www.csdn.com.provider.userContentProvider:Authorities of your own configuration in file sinks
User Resource section (data section) This part is a dynamic change when visitors need to access different resources. This section can be customized
Parse () assumes that you want to convert a string to a URIuri uri = uri.parse ("Content://cn.itcast.provider.personprovider/person")
Action URI because the URI represents the data to manipulate, we often need to parse the URI and fetch the data from the URI. The Android system provides two tool classes for manipulating URIs. They are urimatcher and Contenturis respectively. Master the use of them. will facilitate our development efforts.
Urimatcher class
- Urimatcher.adduri (Authority, Path, code): The match code is the third argument that is passed in by calling the Adduri () method
- Number of authority: defined authority path
- Number of two Path:uri paths
- Number of three code: the matching code returned
- After you have registered the URI that you need to match, you can use the Smatcher.match (URI) method to match the input URI, assuming that the match will return the matching code.
The Urimatcher class is used to match URIs. Its use method is as follows:
Put you need to match the URI path to all the notes on the register, for example the following:
///constant Urimatcher.no_match means no match, no matter what path the return code
urimatcher smatcher = new Urimatcher (urimatcher.no_match);
//Suppose the match () method matches the Content://cn.itcast.provider.personprovider/person path and returns a match code of 1
smatcher.Adduri("Cn.itcast.provider.personprovider", "person", 1);Join required to match URI. Assuming the match will return the match code
//Suppose the match () method matches the content://cn.itcast.provider.personprovider/person/230 path and returns a match code of 2
smatcher.Adduri("Cn.itcast.provider.personprovider", "person/#", 2);#号为通配符
Switch (Smatcher.match(Uri.parse ("CONTENT://CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10"))) {
Case 1
Break
Case 2
Break
DEFAULT://does not match
Break
}
The Contenturis class Contenturis class is used to get the ID part that follows the URI path, and it has two more useful methods:
- The Withappendedid (URI, id) is used to add the ID portion of the path:
- Uri uri = uri.parse ("Content://cn.itcast.provider.personprovider/person")
- Uri Resulturi = Contenturis.withappendedid (URI, 10);
- The resulting URI is: CONTENT://CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10
- The Parseid (URI) method is used to get the ID part from the path:
- Uri uri = uri.parse ("CONTENT://CN.ITCAST.PROVIDER.PERSONPROVIDER/PERSON/10")
- Long PersonID = Contenturis.parseid (URI);
- The result obtained is: 10
Method implementation steps in ContentProvider
- Inheriting the ContentProvider class
- Flags for declaring actions
- Defines the matching code returned by the URI resolution
- Using the Urimatcher class to match URIs
- Instantiating a database Action object in OnCreate ()
- Query method
- Match URI for inference
- Matching a successful query
- Join method
- Match URI for inference
- Match succeeded in joining
- Return: Add a unique ID value via Contenturis.withappendedid
- Delete method
- Match URI for inference
- The match was successfully deleted
- Close the database
- Return: Number of rows deleted
- Change method
- Match URI for inference
- The match was successfully changed
- Close the database
- Return: Number of rows changed
ContentProvider in the change of additions and deletions are based on the Android package good curd
ContentProvider Source code:
Package Com.example.android_sqlite.provider;import Com.example.android_sqlite.database.databasehelper;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 Usercontentprovider extends ContentProvider {//1. Flag of operation private static final String Authoritie = "Www.csdn.com.provider.userContentProvider";//2. Define the matching code returned by URI resolution private static final int QUERY = 1;private static final int INSERT = 2;private static final int UPDATE = 3;private static final int DELETE = 4;private static URIMATC Her urimatcher;private databasehelper dh;//3. Use the Urimatcher class to match uristatic {//Instantiate Urimatcher object. The constant urimatcher.no_match indicates a mismatch regardless of the path of the return code urimatcher = new Urimatcher (urimatcher.no_match);//Matching result code Urimatcher.adduri ( Authoritie, "Query", "Query"), Urimatcher.adduri (Authoritie, "Insert", insert), Urimatcher.adduri (Authoritie, "Update", UPDATE); Urimatcher.adduri (authoritie, "delete", delete);} /** * After Usercontentprovider is created, it is called when other applications first visit Contentprivider. * The ContentProvider will be created */@Overridepublic Boolean onCreate () {dh = new Databasehelper (GetContext ()); return false;} /** * url:http://www.baidu.com/index.html: HTTP protocol visit site * www.baidu.com: Domain part/index.html: site Resources * URI:CONTENT://WW W.csdn.com.provider.usercontentprovider/user * Content://android's ContentProvider rules * Www.csdn.com.provider.userContentProvider: Authorities * User: Resources section (Data section) in file sinks when visitors need to access different resources, This part is dynamic change. This section can be customized * * Urimatcher: Match Uri *//** * Query method */@Overridepublic Cursor query (Uri uri, string[] projection, String Selection,string[] Selectionargs, String sortOrder) {Cursor c = null;//match uri inferred if (Urimatcher.match (uri) = = QUERY) {SQ Litedatabase db = Dh.getreadabledatabase (), C = Db.query ("Users", projection, selection, Selectionargs, Null,null, SortOrder);} else {System.out.println ("The URI of the query operation does not match");} return c;} /** * Returns the type of operation assuming that the operation is multiple records then mine type vnd.android.cursor.div/start * Assuming that the operation's data has only one record then mine type vnd.android.cursor.item/start */@Overridepublic String getType (Uri arg0) { return null;} /** * Insert operation */@Overridepublic URI insert (URI uri, contentvalues values) {Long rowId = 0;if (Urimatcher.match (uri) = = insert {Sqlitedatabase db = Dh.getreadabledatabase (); rowId = Db.insert ("Users", null, Values);d b.close ();} else {System.out.println ("Insert Mismatch");} Add a unique ID value via Contenturis.withappendedid return Contenturis.withappendedid (URI, rowId);} /** * Update operation */@Overridepublic int update (URI uri, contentvalues values, String selection,string[] selectionargs) {//update several lines int Count = 0;if (Urimatcher.match (uri) = = UPDATE) {Sqlitedatabase db = Dh.getwritabledatabase (); count = Db.update ("Users", V Alues, Selection, Selectionargs);d b.close (); return count;} /** * Delete operation */@Overridepublic int Delete (URI Uri, String selection, string[] Selectionargs) {//delete a few lines int count = 0;if (Urimat Cher.match (uri) = = DELETE) {Sqlitedatabase db = Dh.getwritabledatabase (); count = Db.delete ("Users", SELection, Selectionargs);d b.close ();} return count;}}
Androidmanifest.xml
<?XML version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.android_sqlite" android:versioncode= "1" android:versionname= "1.0" > <uses-sdk A ndroid:minsdkversion= "8" android:targetsdkversion= "/> <instrumentation android:name=" Android.te St. Instrumentationtestrunner "android:targetpackage=" Com.example.android_sqlite "> </instrumentation> & Lt;application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string /app_name "Android:theme=" @style/apptheme "> <activity android:name=" com.example.android_sq Lite. Mainactivitysss "android:label=" @string/app_name "> <intent-filter> <acti On android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNC Her "/> ≪/intent-filter> </activity> <uses-library android:name= "Android.test.runner"/> < !--configured ContentProvider--<provider android:name= ". Provider. Usercontentprovider "android:authorities=" Www.csdn.com.provider.userContentProvider "Android:exporte D= "true" > </provider> </application></manifest>
Zhao Yazhi _contentprovider