Android: Introduction to content providers

Source: Internet
Author: User

We learned about the technologies for persisting Android data, including file storage, sharedpreferences storage, and database storage. I don't know if you found out that the data saved using these persistence techniques can only be accessed in the current application. Although both the mode_world_readable and mode_world_writeable modes of operation are provided in the file and sharedpreferences storage to provide other applications with access to the data currently applied, the two modes Both versions of Android 4.2 have been deprecated. Why is it? Because Android authorities no longer recommend this approach for cross-program data sharing, they should use more secure and reliable content provider technology.

Maybe you have some doubts, why should we share the data in our program with other programs? Of course, this depends on the circumstances, such as the account and password, such as private data is obviously not shared to other programs, but some can let other programs to develop two of the basic data, we can still choose to share it. For example, the system phone book program, its database holds a lot of contact information, if the data are not allowed to access third-party programs, I am afraid that many of the functions of the application will be greatly compromised. In addition to the phone book, there are SMS, media Library and other programs to achieve cross-program data sharing function, and the use of the technology is of course the content provider, the following we will be in-depth discussion of this technology.

Introduction to content providers

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.

Unlike two global read-write modes in file storage and sharedpreferences storage, content providers can choose to share only what part of the data, ensuring that the privacy data in our programs is not compromised.

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. So let's start with one, starting with the existing content provider.

7.2 Accessing data from other programs

When an application provides an external access interface to its data through a content provider, any other application can access that part of the data. Programs such as phone books, text messages, media libraries, and so on, in the Android system, provide similar access interfaces, allowing third-party applications to make the most of this data for better functionality. Let's take a look at how the content provider is used.

Basic usage of 7.2.1 Contentresolver

For each application, if you want to access the data that is shared in the content provider, you must use the Contentresolve class to get an instance of the class through the Getcontentresolver () method in the context. Contentresolver provides a series of methods for CRUD operations on data, where the Insert () method is used to add data, the update () method is used to update the data, and the Delete () method is used to delete the data, and the query () method is used to query the data. Any sense of déjà vu? Yes, these are the methods used in Sqlitedatabase for CRUD operations, except that they are slightly different on the method parameters.

Different from the Sqlitedatabase,contentresolver in the method of adding and deleting is not to receive the table name parameter, but instead, using a URI parameter, which is called the content URI. 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

There is no discovery that the content URI can express very clearly what table data we want to access in which program. It is for this reason that the Contentresolver method only receives the Uri object as a parameter, because the system will not know which application table we expect to access because of the use of the table name.

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")

Just call the Uri.parse () method to parse the content URI string into a URI object.

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);

These parameters are similar to those in the query () method in Sqlitedatabase, but overall it is simpler, after all, when accessing data from other programs, there is no need to construct overly complex query statements. The following table provides a detailed explanation of this part of the parameter used.

Qu ery () method parameter

corresponding SQL part

Describe

Uri

From table_name

Specify to query a table under an application

Projection

Select Column1, Column2

Specify the column name of the query

Selection

where column = value

Specify the WHERE constraint

Selectionargs

-

Provide a specific value for a placeholder in the where

By

Order by Column1, Column2

Specify how query results are sorted

When the query is complete, it is still a cursor object, so we can move the data from the cursor object

A read out. The idea of reading is still to traverse all of the cursor's rows by moving the cursor's position, and then fetch the data for the corresponding column in each row, as shown in the following code:

if (cursor! = NULL) {

while (Cursor.movetonext ()) {

String column1 = cursor.getstring (Cursor.getcolumnindex ("Column1"));

int column2 = Cursor.getint (Cursor.getcolumnindex ("Column2"));

}

Cursor.close ();

}

Master the most difficult query operations, the rest of the addition, modification, delete operation is even more. Let's take a look at how to add a piece of data to the Table1 table, the code looks like this:

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

As you can see, the data to be added is still assembled into contentvalues, and then the Contentresolver's insert () method is called, and the URI and Contentvalues are passed in as arguments.

Now if we want to update this newly added data, we can erase the value of the Column1.

Contentresolver the update () method implementation, the code is as follows:

Contentvalues values = new Contentvalues ();

Values.put ("Column1", "" ");

Getcontentresolver (). Update (URI, values, "Column1 =?"). and Column2 =? ", New

String[] {"Text", "1"});

Note that the above code uses the selection and Selectionargs parameters to constrain the data that you want to update to prevent all rows from being affected.

Finally, you can call Contentresolver's Delete () method to remove this data, as shown in the following code:

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

So far, we have learned all the methods of adding and deleting contentresolver. Does it feel very simple? Because this knowledge in the previous chapter in the study of sqlitedatabase you have mastered, the need to pay special attention to only the URI parameter.

Android: Introduction to content providers

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.