Android Content Provider Guides

Source: Internet
Author: User

Android Content Provider Guides

Content providers manages access to structured data sets. They wrap data and provide a mechanism for defining data security.

The Content providers is a standard interface for data connections between different processes .

To get the data in the content provider, you need to use the contentresolver object in the Context in your app as a client To interact with provider.

This provider object is an object of a class that implements the ContentProvider interface. The provider object obtains the data request from the clients, executes the requested action, and returns the result.

  

If you don't want to share data with other apps, you don't have to develop your own provider, but if you need to provide custom search suggestions in your app, or you need to copy and paste complex data and files from your app to other apps, You still need to develop your own provider.

The Android system contains content provider to manage a variety of data, including audio, video, images, personal communications, and more. Can look at this package : android.provider. Under some restrictions, these providers can be accessed by any Android app.

Content Provider Basics

Content provider manages access to the central database, which is part of the Android app and often provides some UI to manipulate the data.

However,content providers is primarily intended for use by other applications, and other applications access provider through a client object.

Together with provider clients, providers provides a continuous, standard interface for accessing data, which also includes some cross-process communication and data access security-related things.

Content provider renders data to an external application like a table in a relational database (but the underlying implementation does not necessarily require a database).

Provider does not require a primary key, and there is no requirement that there must be a column called _id, however, if you want to bind the data to the ListView, you have to have a column called _id.

Visit Provider

An app that wants to access the data in content provider needs to pass through a contentresolver client object.

There are methods in this client object that invoke the same name method in the provider object.

The provider object is an instance of the ContentProvider implementation class.  

  The methods in contentresolver provide the basic "CRUD" (Create, retrieve, update, and delete) data operations.

  Contentresolver objects in a client-applied process, contentprovider objects automatically handle cross-process communication in applications that have provider. ContentProvider is also an abstraction layer, between the data warehouse (the underlying) and the data table (external representation).

In order to access Provider, apps often need to declare some permissions , see Content Provider Permissions.

Content URI

  The Content URI contains the provider symbol name (authority) and a path name (path) that points tothe data table.

When you invoke a client method to access a table in provider, a content URI is required in the parameter.

The Contentresolver object parses the authorityof the URI and uses it to compare with the table of the providers known by the system to resolve out provider.

Contentresolver can then distribute the parameters of the query to the correct provider.

  contentresolver uses the path of the content URI to select the table to access, and a provider typically provides a path for each table.

Like what:

  Content://user_dictionary/words

User_dictionary is authority, words is the pathof table.

content://   (the scheme) indicates that the string is a content URI.

Many providers will allow the ID value to be appended to the URI to access rows in the table.

some useful classes: Uri Uri.builder Contenturis

retrieving Data from the Provider

Data query operations usually need to be executed asynchronously in a non-UI thread, which can refer to loaders Guide.

Querying data from a provider usually takes two steps:

1. Get the Read permission for this provider;

2. Define the query statement to this provider.

An example was written in the official guides, and the relevant considerations related to anti-SQL injection.

/** This defines a one-element String array to contain the selection argument.*/string[] Mselectionargs= {""};//Gets A word from the UIMsearchstring =Msearchword.gettext (). toString ();//Remember to insert code here to check for invalid or malicious input.//If The word is the empty string, gets everythingif(Textutils.isempty (msearchstring)) {//Setting the selection clause to NULL would return all wordsMselectionclause =NULL; mselectionargs[0] = "";} Else {    //constructs a selection clause that matches the word that the user entered.Mselectionclause = UserDictionary.Words.WORD + "=?"; //Moves The user ' s input string to the selection arguments.Mselectionargs[0] =msearchstring;}//Does a query against the table and returns a Cursor objectMcursor =getcontentresolver (). Query (UserDictionary.Words.CONTENT_URI,//The content URI of the words tableMprojection,//The columns to return for each rowMselectionclause//either null, or the word the user enteredMselectionargs,//either empty, or the string the user enteredMsortorder);//The sort order for the returned rows//Some providers return NULL if an error occurs, others throw an exceptionif(NULL==mcursor) {    /** Insert code here to handle the error. Be sure the cursor!     Want to * call ANDROID.UTIL.LOG.E () to Log this error. *     *///If The Cursor is empty, the provider found no matches}Else if(Mcursor.getcount () < 1) {    /** Insert code here to notify the user, the search was unsuccessful. This isn ' t necessarily * an error.     Want to offer the user the option to insert a new row, or re-type the * search term. */} Else {    //Insert code something with the results}

Displaying Query Results

The result of the query is a Cursor that contains the rows that satisfy the query criteria, projection the specified columns.

If there are no rows that meet the criteria, an empty Cursor is returned (Cursor.getcount () is 0).

If an internal error occurs at the time of the query, depending on the provider, the result will be different , it may return null, or it may throw an exception .

The cursor object provides random access to its containing rows and columns.

Using the cursor method, you can iterate through the rows in the result, get the data type of each column, get a column of data, see other properties of the result, and so on.

Some of the cursor 's implementation classes automatically update the data when the provider data changes, or trigger some observer methods when the cursor changes, or both.

The display query data can be bound to the ListView with CursorAdapter or simplecursoradapter .

  To bind the cursor data into the ListView, the cursor must contain a column called _id.

Inserting, Updating, and Deleting Data

Insert

Insert data with Contentresolver.insert (): This method returns the URI of the newly inserted row, for example:content://user_dictionary/words/<id _value>

The data is placed in an object of the Contentvalues class, the _id column is provider automatically maintained and does not need to be written by itself, providers usually _id as the primary key.

In order to get the ID from the URI , you can call the Contenturis.parseid () method.

Update

When you update, you first query based on the selection criteria, and then change the values in it, as in insert, with the contentvalues object.

The method used is contentresolver.update ().

Delete

Delete and query almost, set selection criteria, and then find the row to delete, the client method returns the number of deleted rows.

The method for deletion is Contentresolver.delete ().

When updating and deleting, be aware of the user's malicious actions, see: Protecting Against malicious input.

References

API guides:content Providers

Http://developer.android.com/guide/topics/providers/content-providers.html

Content Provider Basics

Http://developer.android.com/guide/topics/providers/content-provider-basics.html

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.