Android: Create your own content provider

Source: Internet
Author: User

We learned how to access data from other applications in our own programs. Overall, the idea is very simple, just need to get the content URI of the application, and then use Contentresolver for crud operation. But have you ever wondered how the applications that provide the external access interface implement this functionality? How do they ensure data security so that private data is not leaked?

7.3.1 steps to create a content provider

As mentioned earlier, if you want to implement the ability to share data across programs, the official recommendation is to use a content provider that can create your own content provider 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, and the code looks like this:

public class MyProvider extends ContentProvider {

@Override

public Boolean onCreate () {

return false;

}

@Override

Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {

return null;

}

@Override

Public URI insert (URI uri, contentvalues values) {

return null;

}

@Override

public int update (URI uri, contentvalues values, String selection, string[] Selectionargs) {

return 0;

}

@Override

public int Delete (URI Uri, String selection, string[] Selectionargs) {

return 0;

}

@Override

Public String GetType (Uri uri) {

return null;

}

}

In these six methods, I believe most of you are already very familiar with, I will briefly introduce you.

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 the 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 Cursor object is returned in the

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 to delete data from, selection

The and Selectionargs parameters are used to constrain which rows are deleted, and the number of rows deleted is returned as the return value.

6. GetType ()

Returns the corresponding MIME type based on the content URI passed in. You can see that almost every method will have the Uri parameter, this parameter is called Contentresolver to change the method of adding and deleting to pass over. Now, we need to parse the incoming Uri parameter to parse the table and data that the caller expects to access.

To recap, a standard content URI is written like 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 represents the expected access to all the data in the table,

Ending with an ID indicates that you expect to access data that has the corresponding ID in the table. We can use wildcard characters to match the content URIs of both formats, as follows.

1. *: Indicates any character matching any length

2. #: Matches numbers of any length so 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:

public class MyProvider Extendscontentprovider {

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 Urimatcherurimatcher; static {

Urimatcher = Newurimatcher (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_item);

u RI M Atche R . Addur I ("com. Examp L E.ap P . Prov I de R "," table2/# ", Table2_item);

}

......


@Override

Public Cursor query (Uriuri, string[] projection, String selection, string[] Selectionargs, Stringsortorder) {

Switch (Urimatcher.match (URI)) {

Case TABLE1_DIR:

// query all data in the table1 table

Break

Case Table1_item:

// querying single data in the table1 table

Break

Case TABLE2_DIR:

// query all data in the table2 table

Break

Case Table2_item:

// querying single data in the table2 table

Break

Default

Break

}

......

}

......

}

As you can see, there are four new integer constants in MyProvider, where Table1_dir represents access to all data in the Table1 table, Table1_item represents a single piece of data in the Table1 table, and Table2_dir represents all access to the Table2 table Data, Table2_item represents access to 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, and then We can determine what data the caller is expecting to access.

The above code is just a sample of the query () method, in fact, insert (), update (), delete () the implementation of the methods are similar, they will carry the Uri of this parameter, and then also use the Urimatcher match () method to determine which table the caller expects to access, and then to manipulate the data in the table accordingly.

In addition, there is another way you will be more unfamiliar, namely the GetType () method. It 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 provisions.

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>.

So, for content://com.example.app.provider/table1 this content URI, it corresponds to the MIME

Type can be written as:

Vnd.android.cursor.dir/vnd.com.example.app.provider.table1

For CONTENT://COM.EXAMPLE.APP.PROVIDER/TABLE1/1 This content URI, the MIME type it corresponds to can be written as:

Vnd.android.cursor.item/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:

public class MyProvider extends ContentProvider {

......

@Override

Public String GetType (uriuri) {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 ";

Default

Break

}

return null;

}

}

Here, a complete content provider is created, and now any application can use Contentresolver to access the data in our program. So, how do you make sure that your privacy data doesn't leak out, as mentioned earlier? In fact, thanks to the good mechanism of the content provider, this problem has been solved unconsciously. Because all CRUD operations must be matched to the corresponding content URI format, it is certainly not possible to add the URI of the private data to Urimatcher, so this part of the data cannot be accessed by external programs at all, and security issues do not exist.

Android: Create your own content provider

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.