ContentProvider detailed usage records and summaries

Source: Internet
Author: User

The content provider mechanism in Android enables the storage and reading of data in multiple applications. It's also one way to share data across apps,There are files, sharepreference,sqlite databases and other ways to store shared databases, (as well as storage of network data)

But ContentProvider better provides the uniformity of the data sharing interface.

In an Android system, there is no public memory area for multiple apps to share storage data.

Android provides content provider for some of the main data types, such as audio, video, images, and personal contacts. Some of the content provider provided by Android can be found under the Android.provider package. These content provider can be obtained to query the data they contain, provided that the appropriate read permissions have been obtained.


The general sentence: The content provider is an interface for sharing data between applications, and the Android system applies this mechanism to every aspect. For example, a contact provider provides contact data specifically for different applications, and the settings provider provides system configuration information specifically for different applications, including built-in setup applications.


View the official Description document

android.content
Class ContentProvider
Java.lang.Object  Android.content.ContentProvider
All implemented interfaces:
componentcallbacks
Directly known subclasses:
Searchrecentsuggestionsprovider

ContentProvider
 
   
  
Extends Object
Implements Componentcallbacks

As you can tell, ContentProvider is an abstract class; Therefore, it is necessary to inherit and implement the method inside.

The following methods need to be implemented:

    • query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)Which returns data to the caller
    • insert(android.net.Uri, android.content.ContentValues)Which inserts new data into the content provider
    • update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])Which updates existing data in the content provider
    • delete(android.net.Uri, java.lang.String, java.lang.String[])Which deletes data from the content provider
    • getType(android.net.Uri)Which returns the MIME type of data in the content provider

Another common method is the OnCreate () method, in which we can initialize some objects, such as Dbopenhelper.


The following is an example of a complete contentprovider:

Field of person table: PersonID Name Phone amount

The first step: establishing ContentProvider Subclasses

Package Com.my.db;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;import Com.my.service.dbopenhelper;public Class Personprovider extends ContentProvider {private dbopenhelper helper;private final static Urimatcher MATCHER = new Urimatch ER (urimatcher.no_match);p rivate final static int PERSONS = 1;private final static int person = 2;static {Matcher.adduri ("D B.personprovider "," person ", PERSONS); Matcher.adduri ("DB. Personprovider "," person/# ", person);} @Overridepublic Boolean onCreate () {helper = new Dbopenhelper (This.getcontext ()); return true;} @Overridepublic String getType (Uri uri) {switch (Matcher.match (URI)) {case Persons:return "vnd.android.cursor.dir/ Person ", Case Person:return" Vnd.android.cursor.item/person ";d efault:throw new IllegalArgumentException Unknown URI: "+ uri);}} @OverridEpublic uri insert (URI uri, contentvalues values) {sqlitedatabase db = helper.getwritabledatabase (); switch ( Matcher.match (URI)) {case Persons:long rowID = Db.insert ("person", "name", values); Uri Inserturi = Contenturis.withappendedid (URI, rowID), This.getcontext (). Getcontentresolver (). Notifychange (URI, NULL);//Send data change notification return inserturi;default:throw new IllegalArgumentException ("unkonw uri" + uri);}} @Overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {Sqlitedatabase db = Helper.getwritabledata Base (); int num = 0;switch (Matcher.match (URI)) {Case persons:num = db.delete ("Person", selection, Selectionargs); Case Person:long rowID = Contenturis.parseid (URI); String where = "personid=" + rowid;if (selection! = null && "". Equals (Selection.trim ())) {where = where + "and" + selection;} num = db.delete ("Person", where, Selectionargs); Break;default:throw new IllegalArgumentException ("The Is Unknown Uri:" + URI);} return num;} @Overridepublic Cursor query (Uri uRI, string[] projection, string selection,string[] Selectionargs, string sortOrder) {Sqlitedatabase db = Helper.getreadab Ledatabase (); switch (Matcher.match (URI)) {case Persons:return db.query (' person ', projection, selection, Selectionargs , NULL, NULL, sortOrder), case person:long rowid = Contenturis.parseid (URI); String where = "personid=" + rowid;if (selection! = NULL &&! "". Equals (Selection.trim ())) {where + = "and" + selection;} return db.query ("person", projection, where, Selectionargs, Null,null, SortOrder);d Efault:throw New IllegalArgumentException ("This is Unknown URI:" + uri);}} @Overridepublic int update (URI uri, contentvalues values, String selection,string[] selectionargs) {Sqlitedatabase db = he Lper.getwritabledatabase (); int num = 0;switch (Matcher.match (URI)) {Case persons:num = db.update (' person ', values, Selection, Selectionargs); break;case person:long rowid = Contenturis.parseid (URI); String where = "personid=" + rowid;if (selection! = NULL &&! "". Equals (SeleCtion.trim ())) {where + = "and" + selection;} num = db.update ("Person", values, where, Selectionargs); Break;default:throw new IllegalArgumentException ("This is Unknown URI: "+ uri);} return num;}}

Step Two: Register provider


        <application >
<span style= "White-space:pre" ></span><provider            android:name= ". Personprovider "//Note package path            android:authorities=" db here. Personprovider "/>
</application>



Through these two steps, a contentprovider is already complete, and for other applications it is possible to access the person database data in the application.


Here's how to get other apps to access the app's database table data:

The following tests are performed via Androidtestcase:

To build an Android project, the Androidmanifest.xml is mainly configured as follows

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.example.junitest" Android: Versioncode= "1" android:versionname= "1.0" > <application android:allowbackup= "true" Android:icon = "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <us Es-library android:name= "Android.test.runner"/> <activity android:name= ". Mainactivity "android:label=" Test "> <intent-filter android:label=" Test "> & Lt;action android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.categor Y.launcher "/> </intent-filter> </activity> </application> <instrumentatio    n android:name= "Android.test.InstrumentationTestRunner" android:targetpackage= "Com.example.junitest" > </instrumentation></manifest>


Create a class with the table to test the contentprovider, and note the packet path problem



Package Com.example.test;import Android.content.contentresolver;import Android.content.contentvalues;import Android.database.cursor;import Android.net.uri;import Android.test.androidtestcase;public class ProviderTest Extends Androidtestcase {public void Testinsert () {uri uri = Uri.parse ("content://db. Personprovider/person "); Contentresolver resolver = This.getcontext (). Getcontentresolver (); Contentvalues values = new Contentvalues (), Values.put ("name", "Test"), Values.put ("Phone", "123456789"), Values.put (" Amount ", 9999); Resolver.insert (URI, values);} public void Testdelete () {//URI URI = Uri.parse ("content://db. Personprovider/person ");//Contentresolver resolver = This.getcontext (). Getcontentresolver ();//Resolver.delete (URI , NULL, NULL); Uri uri = Uri.parse ("content://db. PERSONPROVIDER/PERSON/52 "); Contentresolver resolver = This.getcontext (). Getcontentresolver (); Resolver.delete (URI, NULL, NULL);} public void Testupdate () {//URI URI = Uri.parse ("content://db. Personprovider/person ");//ConteNtresolver resolver = This.getcontext (). Getcontentresolver ();////contentvalues values = new Contentvalues ();// Values.put ("Phone", "");//Resolver.update (URI, values, NULL, NULL); Uri uri = Uri.parse ("content://db. Personprovider/person/45 "); Contentresolver resolver = This.getcontext (). Getcontentresolver (); Contentvalues values = new Contentvalues () values.put ("Phone", "111111111111111111111111111111"); Resolver.update ( URI, values, NULL, NULL);} public void Testquery () {//URI URI = Uri.parse ("content://db. Personprovider/person ");//Contentresolver resolver = This.getcontext (). Getcontentresolver ();//CURSOR cursor = Resolver.query (URI, NULL, NULL, NULL, and NULL); Uri uri = Uri.parse ("content://db. Personprovider/person/45 "); Contentresolver resolver = This.getcontext (). Getcontentresolver (); cursor cursor = resolver.query (URI, NULL, NULL, NULL, NULL), while (Cursor.movetonext ()) {String name = cursor.getstring (cu Rsor.getcolumnindex ("name")); SYSTEM.OUT.PRINTLN (name);}}}


Run as Android JUnit test can be tested.

Summarize:


Content providers is one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data are used by multiple applications and must being stored in a content provider. If you don ' t need to share data amongst multiple applications you can use a database directly via SQLiteDatabase .

For more information, read Content Providers.

When a request is made via a, the ContentResolver system inspects the authority of the given URI and passes the request to the Conten T provider registered with the authority. The content provider can interpret the rest of the URI however it wants. The UriMatcher class is helpful for parsing URIs.


ContentProvider detailed usage records and summaries

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.