Android content provider details 6

Source: Internet
Author: User
Create a content provider

The content provider Manages access to the central data warehouse. You implement a provider that implements one or more classes in an android application, and adds some elements in the manifest file. You implement a subclass of contentprovider, which serves as the interface between your provider and other applications. Although content providers aims to provide data to other applications, you can also create an activity in your own application to allow users to query and modify the data managed by your provider.

Preparations before creation

Before creating a provider, you need to do the following:
1. Determine whether you need a content provider. To provide one or more of the following features, you need to create a content provider:
You want to provide complex data or files to other applications.
You want to use protection to copy complex data from your application to other applications.
You want to use the search framework to provide Custom Search recommendations.
If it is used inside your application, your provider does not need to use the SQLite database.
2. If you have not made a decision, read the topic content provider basics to learn more about provider.
Next, follow these steps to create your provider:
1. design the original storage method for your data. A content provider provides data in two ways:
File data
Data stored in files, such as video, video, and audio. Store files in the private space of your application. To respond to requests sent from other applications to a file, your provider can provide a handle for the file.
"Structured" Data
Refers to the data, arrays, or small structures stored in the database. Data is stored as tables. A row represents a piece of data, just like a Member or entry in the list. A column represents a part of the data, such as the name of a person or the price of a person. A common method to store these types of data is to use the SQLite database, but you can also use other forms. For more information about the storage methods in the Android system, see the design data storage section.
2. Define the contentprovider class and its methods. This class is the interface between your data and other things in the Android system. For more information about this class, see the section implementing the contentprovider class.
3. Define the Authority string, content Uris, and column name of the provider. If you want the provider's application to process intent, you also need to define the intent action, additional data, and flag. Define the permissions required for applications that want to access your data. You should consider defining these values as contracts into another separate contract class. This class will be displayed to other developers in the future. For more information about content Uri, see the design content URI. Section. For more information about intent, see intent and data operations.
4. Add other optional content, such as sample data or abstractthreadedsyncadapter, to synchronize data between providers and cloud-based data.

Define data storage

A content provider is a data interface for structured storage. Before creating this interface, you must determine how to store data. You can store data in any way you like, and then design an interface for reading and writing data.
The following are some data storage technologies available in Android:
1. The Android system contains an SQLite database API, which is used by Android providers to store table-class data. The sqliteopenhelper class helps you create databases, while the sqlitedatabase class is the basic class for operating databases.
Remember that you do not have to use a database to implement your data warehouse. A provider is represented externally as a table set, similar to a relational database, but the internal implementation of the provider can be different from this.
2. for data storage, Android has a variety of file-oriented APIs. For more information about Object Storage, see topic data storage. If you design a provider to provide media-related data, such as audio and video, you can mix table data and files in the provider.
3. to process network data, use classes in java.net and android.net. You can also synchronize network data to local data storage (such as databases), and then provide the data in the form of tables or files. The sample sync adapter demonstrates this synchronization technology.

Thinking about data design

Below are some tips for designing the data structure of your provider:
1. The table data should always have a "primary key" column, which is used to manage a unique value representing each row. You can use this value to link a row to related rows in other tables (that is, the "foreign key "). Although you can take any name for this column, use basecolumns. _ id is the best choice, because when you associate the query result of a provider to a listview, you need a column named _ id.
2. If you want to provide a bitmap image or other very large file-oriented data, store it in the file and then provide it indirectly, instead of directly storing data in a table. If you do this, you also need to inform the provider users that they need to use a contentresolver file method to operate the data.
3. Use the Data Type of a large binary object (BLOB) to store data of an indefinite size or no fixed structure. For example, you can use a blob column to store protocol buffer or JSON structure.
You can also use a blob to implement an independent table. In this table, you define a primary key column, a MIME type column, and one or more common blob columns. The meaning of the data in the Blob column is indicated by the values in the mime column. This allows you to store different types of data in each row of a table. The contactscontract. Data Table of the contact provider is an example of an independent mode table.

Design Content: Uris

A content URI indicates the data in a provider. The content URI contains the symbolic name of the entire provider (his authority) and a name pointing to a table or file. The optional ID part points to an independent row in the table. Each data operation method of contentprovider has a content URI as a parameter; this allows you to decide the table, row, or file to operate.
The basis of the Content URI is described in the base of the title content provider.

Design an authority

A provider usually has a single authority, which serves as its internal Android name. In order to avoid conflicts with other providers, you should use the Internet domain name method (but rather inverted) as the basic name of your provider authority. Because this suggestion is also used for the android package name, you can define your provider authority as an extension that contains the package name of this provider. For example, if your android package name is com. example. <appname>, you should name your provider authority as com. example. <appname>. provider.

Define a path Structure

Developers usually create content URI from authority by adding a path pointing to an independent table. For example, if you have two tables Table1 and Table2, the content URI you merged from the authority in the preceding example is com. example. <appname>. provider/Table1 and COM. example. <appname>. provider/Table2. The path does not have to have only one parameter, and each layer of the path does not have to be a table.

ID of the URI of the processed content

For convenience, the provider accepts to put the ID of a row at the end of the URI to provide access to a row in the table. For convenience, the provider compares the _ ID column of the ID and table, and then executes the Operation Request for matching rows ..
This convenience helps to use a common design pattern when an application operates on a provider. The application sends a query to the provider and then uses a cursoradapter in a listview to display the result cursor. The definition of cursoradapter requires a column named _ id in cursor.
You can then select a row in the row displayed in the UI to view or modify the data. The app then obtains the corresponding row from the cursor behind the listview, obtains the _ id value of the row, adds this value to the content Uri, and then sends the operation request to the provider. Then, query or modify the row specified by the user.

Content URI Mode

To help you select the action you want to execute with the data Uri, the provider API contains a simple class urimatcher, which maps the "mode" of the content URI to an integer. You can use this integer in a switch statement to select a content URI that matches a pattern or multiple URIs to execute an action.
A content URI uses wildcards to match other content Uris:
*: Match any valid string of any length.
#: Match strings of any length consisting of digits.
Let's look at an example of how to design and encode content URI. Assume that the authority of a provider is com. example. App. provider. It can identify the content URI pointing to each table as follows:
1 content: // com. example. App. provider/Table1: A table named table1.
2 content: // com. example. App. provider/Table2/dataset1: A table named dataset1.
3 content: // com. example. App. provider/Table2/dataset2: A table named dataset2.
4 content: // com. example. App. provider/table3: A table named table3.
The provider also recognizes the content URIs with the ID of a row, for example, content: // com. example. App. provider/table3/1 points to row 1 in table 3.
The following content URI mode may also appear:
Content: // com. example. App. provider /*
Matches the task content URI in the provider.
Content: // com. example. App. provider/Table2 /*:
Matches a content URI in dataset1 and dataset2, but does not match the content URI in Table1 or table3.
Content: // COM. example. app. provider/table3/#: match any row in table 3, such as content: // COM. example. app. provider/table3/6 points to row 6.
The following code snippet demonstrates how urimatcher methods work. This code points to the table by using content URI mode content: // <authority>/<path>, using content: // <authority>/<path>/<ID> points to a separate row. The URI pointing to the entire table and the URI pointing to a single row are processed in different ways.
The adduri () method maps an authority and path to an integer. Method Android. content. urimatcher # match (URI) match ()} returns an integer corresponding to the URI. A switch statement selects between querying the entire table and querying a single record:

Public class exampleprovider extends contentprovider {... // create a urimatcher object Private Static final urimatcher surimatcher;.../** here, it is a call to adduri. The provider should be able to recognize all content Uris. * However, In this fragment, only the call to Table 3 is demonstrated. */.../** The multi-row mode in ing Table 3 is 1. Note that Wildcards are not used in the path. */Surimatcher. adduri ("com. example. App. provider", "table3", 1);/** ing single row mode is 2. In this example, the wildcard "#" is also used. * "Content: // COM. example. app. provider/table3/3 "can match this mode, but *" content: // COM. example. app. provider/table3. */Surimatcher. adduri ("com. example. app. provider "," table3/# ", 2 );... // implement contentprovider. query () Public cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder ){... /** select a table to be queried and select the sorting order based on the Code returned by the input Uri. * Only Table 3 is shown here. */Switch (surimatcher. match (URI) {// If the input URI points to the entire table 3 Case 1: If (textutils. isempty (sortorder) sortorder = "_ id ASC"; break; // If the input URI points to a single row case 2:/** because this URI points to a single row, so the _ id part appears. * Obtain the last path segment from the URI. It is the _ id value. * Then, add the value to the where substatement of the query statement. */Selection = Selection + "_ id =" URI. getlastpathsegment (); break; default :... // If the URI cannot be identified, you should handle some errors here.} // Call the code for the actual query}

Another class, contenturis, provides a simple way to process the ID part of the content Uri. Class Uri and Uri. Builder contain a simple method for analyzing existing URI objects and creating new objects.

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.