Getting Started with Android (13) content provider

Source: Internet
Author: User

Original link: http://www.orlion.ga/612/

Content Provider is primarily used to implement data sharing among different applications, providing a complete set of mechanisms that allow one program to access data from another program while guaranteeing the security of the data being accessed. Currently, using a content provider is a standard way for Android to share data across programs. There are two general uses of content providers, one is to use an existing content provider to read and manipulate data in the corresponding program, and to create your own content provider to provide external access to the data of our programs.

One, access to data in other programs

Android comes with a phone book, SMS, Media Library and other programs that provide external access interfaces that third-party programs can use to develop

1. Basic usage of Contentresolver

If you want to access the data for the content provider to use the Contentresolver class, you can get an instance of the class by using the Getcontentresolver () method in the context. Contentresolver provides a number of methods for CRUD operations on data, namely insert () \update () \delete () \query (), similar to Sqlitedatabase, except that the parameters are different. The crud methods in Contentresolver do not accept table names, but instead use URI parameters, which are called content URIs. The content URI establishes a unique identifier for the data in the content provider, which consists mainly of two parts, the permission (authority), and the path. Permissions are used to differentiate between different applications and are typically named in the same way that the package name is used to avoid conflicts. For example, a program's package name is Com.example.app, then the program's corresponding permissions can be named Com.example.app.provider. Paths are used to differentiate between different tables in the same application, and are usually added to the back of the permission. For example, in a program's database there are two tables, table1 and table2, then the path can be named/table1 and/table2, and then the permissions and paths are combined, the content URI becomes com.example.app.provider/ Table1 and Com.example.app.provider/table2. However, it is difficult to recognize that these two strings are two content URIs, and we also need to add a protocol declaration to the header of the string. Therefore, the most standard format for content URIs is as follows:

Content://com.example.app.provider/table1content://com.example.app.provider/table2

After we get the content URI string, we also need to parse it into a URI object before it can be passed in as a parameter. The parsing method is also fairly straightforward, as shown in the code below:

Uri uri = uri.parse ("Content://com.example.app.provider/table1")

Now we can use this URI object to query the data in the Table1 table, as shown in the code below:

cursor cursor = getcontentresolver (). Query (URI, projection, selection, Selectionargs, SortOrder);

A cursor object is still returned when the query is complete.

To add a data operation:

Contentvalues values = new Contentvalues (), Values.put ("Column1", "text"), Values.put ("Column2", 1); getcontentresolver (). Insert (URI, values);

To update data operations:

Contentvalues values = new Contentvalues (), Values.put ("Column1", "" "), Getcontentresolver (). Update (URI, values," Column1 =? and Column2 =? ", newstring[] {" Text "," 1 "});

To delete a data operation:

Getcontentresolver (). Delete (URI, "Column2 =?", new string[] {"1"});

Second, create your own content provider

1. Steps to create a content provider

     can create a content provider of its own by creating a new class to inherit ContentProvider. There are six abstract methods in the ContentProvider class, and we need to rewrite all six methods when we use subclasses to inherit it. The new MyProvider inherits from ContentProvider, as shown in the following code:

package ga.orlion.contactdemo;import android.content.contentprovider;import  android.content.contentvalues;import android.database.cursor;import android.net.uri;public  class myprovider extends contentprovider {@Overridepublic  boolean oncreate ()  {// todo auto-generated method stubreturn false;} @Overridepublic  cursor query (uri uri, string[] projection, string selection ,  string[] selectionargs, string sortorder)  {// TODO Auto-generated  Method stubreturn null;} @Overridepublic  string gettype (Uri uri)  {// todo auto-generated method  stubreturn null;} @Overridepublic  uri insert (uri uri, contentvalues values)  {// TODO  Auto-generated method stubreturn null;} @Overridepublic  int delete (Uri uri, string selEction, string[] selectionargs)  {// todo auto-generated method stubreturn  0;} @Overridepublic  int update (Uri uri, contentvalues values, string selection,  string[] selectionargs)  {// todo auto-generated method stubreturn 0;}}
      1. OnCreate ()

        Called when the content provider is initialized. Operations such as creating and upgrading a database are usually done here, and returning True indicates that the content provider was initialized successfully and that returning false indicates a failure. Note that the content provider is initialized only if there is a contentresolver attempt to access data in our program.

      2. Query ()

        Query data from the content provider. Use the URI parameter to determine which table to query, the projection parameter to determine which columns to query, the selection and Selectionargs parameters to constrain which rows to query, the SortOrder parameter to sort the results, and the results of the query to be stored in the Returned in the cursor object.

      3. Insert ()

        Adds a piece of data to the content provider. Use the URI parameter to determine the table to add to, and the data to be added is saved in the values parameter. When added is complete, returns a URI that represents the new record.

      4. Update ()

        Updates the data already in the content provider. Using the URI parameter to determine which table data is updated, the new data is saved in the values parameter, and the selection and Selectionargs parameters are used to constrain which rows are updated, and the number of rows affected is returned as the return value.

      5. Delete ()

        Deletes data from the content provider. Use the URI parameter to determine which table data is deleted, the selection and Selectionargs parameters are used to constrain which rows are deleted, and the number of rows deleted is returned as a return value

      6. GetType ()

        Returns the corresponding MIME type based on the content URI passed in.

Almost every method will have the URI of this parameter, this parameter is called Contentresolver to delete the additions and deletions of the method passed over. Now, we need to parse the incoming URI parameter to parse the table and data that the caller expects to access.

A standard content URI notation is this: Content://com.example.app.provider/table1. This means that the caller expects to access data from the Table1 table of the Com.example.app application. In addition, we can add an ID to the content URI, as follows:

CONTENT://COM.EXAMPLE.APP.PROVIDER/TABLE1/1. This means that the caller expects to access data that is ID 1 in the Table1 table of the Com.example.app application.

The format of the content URI is mainly only the above two, at the end of the path is expected to access all the data in the table, the end of the ID represents the expected access to the table has the corresponding ID data. We can use wildcard characters to match the content URI of both formats, as follows:

      1. *: Indicates any character that matches any length

      2. #: Indicates a match for any length of number

Therefore, a content URI format that matches any table can be written as: content://com.example.app.provider/*. A content URI format that matches any row of data in the Table1 table can be written as: content://com.example.app.provider/table1/#.

Next, we can easily implement the function of matching content URIs with the Urimatcher class. A Adduri () method is provided in the Urimatcher, which receives three parameters, which can be passed into the permission, path, and a custom code, respectively. Thus, when calling Urimatcher's match () method, a URI object can be passed in, and the return value is a custom code that matches the URI object, and with this code we can determine which table the caller expects to access. Modify the code in the MyProvider as follows:

package com.example.contactdemo;import android.content.contentprovider;import  android.content.contentvalues;import android.content.urimatcher;import android.database.cursor; Import android.net.uri;public class myprovider extends contentprovider {public  static final int TABLE1_DIR = 0;public static final int  table1_item = 1;public static final int table2_dir = 2;public  static final int table2_item = 3;private static urimatcher urimatcher; Static {urimatcher = new urimatcher (Urimatcher.no_match); Urimatcher.adduri (" Com.example.app.provider ", " table1 ",  table1_dir); Urimatcher.adduri (" Com.example.app.provider ",  "table1/#",  table1_item), Urimatcher.adduri ("Com.example.app.provider",  "Table2",  table2_dir); Urimatcher.adduri ("Com.example.app.provider",  "table2/# ",  table2_item);} @Overridepublic  cursor query (uri uri, string[] projection, string selection ,  string[] selectionargs, string sortorder)  {switch  (Urimatcher.match (URI))  {case TABLE1_DIR://  query all data in Table1 table break;case table1_item://  query table2 single data in table Break;case  TABLE2_DIR://  query all data in the Table2 table break;case table2_item://   query the Table2 table for a single data break;default: break;} ....} ...}

As you can see, there are four new integer constants in MyProvider, where Table1_dir represents all the data in the Table1 table, Table1_item represents a single piece of data in the Table1 table, Table2_dir Represents access to all data in the Table2 table, and Table2_item represents a single piece of data in the Table2 table. Then in the static code block we create an instance of Urimatcher, and call the Adduri () method, passing in the expected matching content URI format, note that the path parameter passed in here can use wildcard characters. Then when the query () method is called, the incoming URI object is matched by the Urimatcher's match () method, and if a content URI format in Urimatcher is found to successfully match the URI object, the corresponding custom code is returned. Then we can determine what data the caller expects to be accessing. The above code is just a sample of the query () method, in fact, insert (), update (), delete () the several Parties

The implementation of the method is similar, they will carry the URI of this parameter, and then also use Urimatcher's match () method to determine what the caller expects to access the table, and then the data in the table corresponding operation is possible.

The GetType () method is a method that all content providers must provide to get the MIME type that the URI object corresponds to. A content URI corresponding to the MIME string is mainly composed of three components, Android to these three parts made the following format:

      1. Must start with VND.

      2. If the content URI ends with a path, then android.cursor.dir/, followed by android.cursor.item/if the content URI ends with an ID.

      3. Finally, connect the vnd.<authority>.<path>.

Therefore, for content://com.example.app.provider/table1 this content URI, its corresponding MIME type can be written as: vnd.android.cursor.dir/ Vnd.com.example.app.provider.table1

Now we can continue to refine the content in MyProvider, this time to implement the logic in the GetType () method, as shown in the code below:

@Overridepublic String getType (Uri uri) {switch (Urimatcher.match (URI)) {case Table1_dir:return " Vnd.android.cursor.dir/vnd.com.example.app.provider.table1 "; case Table1_item:return" vnd.android.cursor.item/ Vnd.com.example.app.provider.table1 "; case Table2_dir:return" vnd.android.cursor.dir/ Vnd.com.example.app.provider.table2 "; case Table2_item:return" vnd.android.cursor.item/ Vnd.com.example.app.provider.table2 ";d Efault:break;} return null;}

Getting Started with Android (13) content provider

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.