The use of "Android Essentials" content provider ContentProvider

Source: Internet
Author: User
Tags define abstract

1. What is ContentProviderFirst, ContentProvider (content provider) is one of the four components of Android, but it may be less used in general development. ContentProvider provides a unified interface for data sharing between different software. That is, if we want other applications to use the data in our own program, we can use ContentProvider to define an open interface, so that other applications can use the files we apply, the information stored in the database. Of course, the need to share information with other applications may be rare, but in Android, many systems bring their own applications, such as contact information, image libraries, audio libraries and other applications, so they use the contentprovider mechanism to expose data to other applications. Therefore, we still want to learn the basic use of ContentProvider, in the encounter to get contact information, image Library, audio library and other needs, in order to better realize the function 2. How to define a ContentProviderThe Android system provides a unified interface to allow us to expose data better, so we define abstract class ContentProvider, so if we want to provide data externally, we need to inherit ContentProvider, And the following methods are implemented:
onCreate () is called when our provider is initialized, we should do some initialization in this methodquery () method for returning data to the callerInsert () inserts to allow external apps to insert data into the content providerUpdate () updates to update the data of the content providerDelete () deletes dataGetType returns the MIME Type of the content provider
The above methods, when we inherit from ContentProvider, Eclipse will automatically add to us, but this does not mean that each of us requires a custom implementation. If we only want to provide data to other applications and not allow other apps to modify our data, then we only need to implement OnCreate (), GetType () and query () Three methods, the other three methods we can according to business requirements, or not implementation.
because of the general use of contentprovider to externally expose the database information, this article will use ContentProvider to other applications to expose the database information as an example to explain the basic use of contentprovider.
The creation and use of SQLite database in Android, this article is no longer introduced, not clear please read this articlethe simple and practical application of SQLite database

Assuming that the reader has learned the use of the SQLite database and has established the database, let's start writing our contentprovider. because the annotation parsing is more detailed, so there is not much to explain
/** * Content Provider * * @author Zhaokaiqiang * @time June 6, 2014 */public class Studentprovider extends ContentProvider {//Database operation class,  Used to get sqlitedatabaseprivate mydbopenhelper dbhelper;private static final int STUDENT = 1;private static final int STUDENTS = The 2;//Urimatcher class is a very important class, because we need to determine the execution of the corresponding operation according to the incoming URI, private static final urimatcher MATCHER = new Urimatcher ( Urimatcher.no_match)///Static code block for initializing MATCHER requires matching uristatic {//Matcher.adduri (hostname (used to uniquely indicate a contentprovider, This need is the same as the authorities attribute in the manifest file), the path (which can be used to represent the data we want to manipulate, the construction of the path should be based on the business), the return value (used to match the URI, as a matching return value)); Matcher.adduri ("Com.example.mydbdemo.StudentProvider", "Student", STUDENTS); Matcher.adduri ("Com.example.mydbdemo.StudentProvider", "student/#", student);} Initialization of Data @overridepublic Boolean onCreate () {dbhelper = new Mydbopenhelper (GetContext ()); return false;} Query//If the URI is content://com.example.mydbdemo.studentprovider/student//, it means querying all the data in the Student table//If the URI is content:// The com.example.mydbdemo.studentprovider/student/6//represents the data in the student table id=6 @overridepublic CUrsor query (Uri uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {Sqlitedatabase db = Dbhelper.getreadabledatabase ();//determine the exact match of the incoming URI to achieve different business requirements switch (Matcher.match (URI)) {//query all student information case STUDENTS ://db.query (indicates that the column to be queried (is a string array), where condition, parameter in the Where condition, groupBy, having, sortOrder); return db.query ("Student", Projection, selection, Selectionargs, NULL, NULL, sortOrder);//Query The student's information for an ID case student://take out the Idlong ID of the data we want to query = Contenturis.parseid (URI); String where = "id=" + id;//stitching selection query information into our Where condition if (selection! = NULL &&! "". Equals (selection)) {where = Selection + "and" + where;} Return Db.query ("Student", projection, where, Selectionargs, NULL, NULL, sortOrder);//If the URI does not match, throw an exception with an illegal argument default:throw New IllegalArgumentException ("Unkwon Uri:" + uri.tostring ());}} Insert @overridepublic URI Insert (URI uri, contentvalues values) {sqlitedatabase db = Dbhelper.getwritabledatabase (); Switch (Matcher.match (URI)) {case Students:long id = Db.insert ("Student "," name ", values), return Contenturis.withappendedid (URI, id);d efault:throw new IllegalArgumentException (" URI does not match ");}} Delete data @overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {Sqlitedatabase db = Dbhelper.getwrit Abledatabase (); int count = 0;switch (Matcher.match (URI)) {Case students:count = db.delete ("Student", selection, Selectionargs); return count;case Student:long id = contenturis.parseid (URI); String where = "id=" + id;if (selection! = NULL &&! "". Equals (selection)) {where = Selection + "and" + where;} Count = Db.delete ("Student", where, Selectionargs); return count;default:throw new IllegalArgumentException ("Unkwon Uri : "+ uri.tostring ());}} Update Data @overridepublic int update (URI uri, contentvalues values, String selection, string[] Selectionargs) { Sqlitedatabase db = Dbhelper.getwritabledatabase (); int count = 0;switch (Matcher.match (URI)) {Case Students:count = Db.up Date ("Student", values, selection, Selectionargs); return count;case Student:loNg id = contenturis.parseid (URI); String where = "id=" + id;if (selection! = NULL &&! "". Equals (selection)) {where = Selection + "and" + where;} Count = db.update ("Student", values, where, Selectionargs); return count;default:throw new IllegalArgumentException (" Unkwon Uri: "+ uri.tostring ());}} Used to get the MIME type@overridepublic String getType (Uri uri) {switch (Matcher.match (URI)) {case Student:return " Vnd.android.cursor.item/student ", Case Students:return" Vnd.android.cursor.dir/student ";d efault:throw New IllegalArgumentException ("Unkwon Uri:" + uri.tostring ());}}}

After we have defined our contentprovider, becauseContentProvider Data is one of the four components, so we also need to register in the androidmanifest manifest file in order to use, the following is the registration information
<!--do not forget exported this property, if not added, may cause external program Access failure, error message for permission denied--<!-- Authorities this property is the value of the first parameter when we use the Adduri method in ContentProvider-        <provider            android:name= " Com.example.mydbdemo.StudentProvider "            android:exported=" true "            android:authorities=" Com.example.mydbdemo.StudentProvider ">        </provider>

Note that the provider declaration, like activity, is declared at the application node.
at this point, we have completed our own contentprovider of life, and other applications can now use the data information we expose to the outside.
3. How external applications use our ContentProviderwe have defined our own contentprovider, so how can external applications be invoked? Next, I'll create a new test unit project to complete the testing of the various methods of ContentProvider
Add a method test
Test for adding data using contentprovider public void Testadd () throws Throwable {//Get Contentresolver object, Complete the call to ContentProvider contentresolver contentresolver = This.getcontext (). Getcontentresolver ();//Build our UiR, this Uriuri Inserturi = Uri.parse ("content://com.example.mydbdemo.studentprovider/student"); Contentvalues values = new Contentvalues (), Values.put ("name", "Zhaokaikai"), Values.put ("Age", "the") Values.put ("School "," bbbb ");//The return value is the URI address of the data we just inserted into the URI uri = Contentresolver.insert (Inserturi, values); LOG.I (TAG, uri.tostring ());}

Delete method Test
Test for deleting data using contentprovider public void Testdelete () throws Throwable {Contentresolver Contentresolver = This.getcontext (). Getcontentresolver ();//delete student information with ID 6 Uri Deleteuri = Uri.parse ("content://com.example.mydbdemo.studentprovider/ STUDENT/6 "); Contentresolver.delete (Deleteuri, NULL, NULL);}


Modify Method Test
Test for updating data using contentprovider public void Testupdate () throws Throwable {Contentresolver Contentresolver = This.getcontext (). Getcontentresolver ();//Update id = 6 for student information Uri Updateuri = Uri.parse ("content://com.example.mydbdemo.studentprovider/ STUDENT/6 "); Contentvalues values = new Contentvalues (), Values.put ("name", "Testup"), Values.put ("Age", "101"), Values.put ("school"); , "CCCCC"); Contentresolver.update (Updateuri, values, NULL, NULL);}

Test for querying data using contentprovider public void Testfind () throws Throwable {Contentresolver contentresolver = This.getcontext () . Getcontentresolver ();//This Uri is used to query all data, if you query the data of an ID, build the following Uri//uri Selecturi = Uri.parse ("content:// com.example.mydbdemo.studentprovider/student/the ID to be queried "); Uri Selecturi = Uri.parse ("content://com.example.mydbdemo.studentprovider/student"); cursor cursor = contentresolver.query (Selecturi, NULL, NULL, NULL, "ID desc"), while (Cursor.movetonext ()) {int id = cursor . GetInt (Cursor.getcolumnindex ("id")); String name = cursor.getstring (Cursor.getcolumnindex ("name")); int age = Cursor.getint (Cursor.getcolumnindex ("Age")); String School = cursor.getstring (Cursor.getcolumnindex ("school")); LOG.I (TAG, "id=" + ID + ", name=" + name + ", age=" + Age + ", school=" +school);}}

All of the above methods have been unit tested.
Well, at this point, we use ContentProvider to achieve in the third-party application of our application of the database for the increase and deletion of the operation, if in doubt, please leave a message.









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.