Android Content Provider Guides

Source: Internet
Author: User

Android Content Provider Guides

 

Content Providers Manages access to structured datasets. They encapsulate data and provide a mechanism to define data security.

Content providers is the standard interface for data connection between different processes.

To obtain data in the content provider, you must use ContextInContentResolverObject asClientTo interact with the provider.

ThisProviderThe object is an implementationContentProviderInterface Class Object. The Provider object obtains the data request from clients, executes the request action, and then returns the result.

  

If you do not want to share data with other applications, you do not need to develop your own provider. However, if you need to provide Custom Search recommendations in the application, or you need to copy and paste complex data and files from your application to other applications, you still need to develop your own provider.

The Android system contains content providers for managing various types of data, including audio, video, images, and personal communication information. Take a look at this package: Android. provider. Under some restrictions, these providers can be accessed by any Android Application.

Content Provider Basics

Content providers manage access to central databases, which is part of Android applications and often provide some UIS for data operations.

However,Content providers are mainly used by other applications. Other applications access providers through a client object.

Together with providers and provider clients, providers provide continuous and standard interfaces to access data, including cross-process communication and data access security.

The Content provider presents data to external applications in a way similar to a table in a relational database (but the underlying implementation does not necessarily require a database ).

The provider does not require a primary key or a column named _ ID. However, if you want to bind data to ListView, you must have a column named _ ID.

Access provider

To access data in the content provider, an application must useContentResolverClient object.

Some methods in this client object call methods of the same name in the provider object.

The provider object is ContentProvider. 

  ContentResolverThe methods in provide basic "CRUD" (create, retrieve, update, and delete) data operations.

  ContentResolverThe object is in the process of the client application, ContentProviderObjects in applications with providers automatically process cross-process communication. ContentProviderIt is also an abstraction layer, located between the data warehouse (bottom layer) and the data table (external performance.

To access the provider, the application usually needs to declare somePermission, SeeContent Provider Permissions.

Content URI

  Content URIContains the symbolic name of the provider (AuthorityAnd a path name pointing to a data table (Path).

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

The ContentResolver object will parse the URI authority and use it to compare with the table provided by the system to resolve the provider.

Then ContentResolver can distribute the query parameters to the correct provider.

  ContentResolverThe path of content URI is used to select the table to be accessed. A provider usually provides a path for each table.

For example:

  Content: // user_dictionary/words

User_dictionary isAuthority, Words is tablePath.

Content ://(The scheme) indicates that this string is a content URI.

 

Many providers allow adding the ID value behind the URI to access rows in the table.

Some useful classes: Uri. Builder ContentUris

Retrieving Data from the Provider

Data Query operations usually need to be performed asynchronously in a non-UI thread. For details, refer to Loaders guide.

It usually takes two steps to query data from a provider:

1. Get the read permission of this provider;

2. Define the query statement to this provider.

The official Guides has provided examples and discussed anti-SQL injection and other related considerations.

/* * 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 will return all words    mSelectionClause = 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 table    mProjection,                       // The columns to return for each row    mSelectionClause                   // Either null, or the word the user entered    mSelectionArgs,                    // Either empty, or the string the user entered    mSortOrder);                       // 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 not to use the cursor! You may 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 that the search was unsuccessful. This isn't necessarily     * an error. You may want to offer the user the option to insert a new row, or re-type the     * search term.     */} else {    // Insert code here to do something with the results}

 

Displaying query results

The query result is CursorThe column specified by projection contains the rows that meet the query conditions.

If no row meets the condition, an empty Cursor (Cursor. getCount () is returned as 0 ).

If an internal error occurs during the query, the result varies according to the specific provider.May return null or throw an exception..

The Cursor object provides random access to its contained columns.

Using the method in Cursor, You can traverse the rows in the result to obtain the data type of each column, get the data of a certain column, and view other attributes of the result.

Some CursorThe implementation class will automatically update the data when the provider data changes, or inspire some observer methods when the Cursor changes, or both have.

Display query data available CursorAdapterOr useSimpleCursorAdapterBind to ListView.

To bind Cursor data to the ListView, the cursor must contain a column named _ ID.

Inserting, Updating, and Deleting Data

Insert

Data insertion ContentResolver. insert (): This method will return the URI of the newly inserted row, for example:Content: // user_dictionary/words/<id_value>

Data is stored inContentValuesIn the class object, the _ ID column is automatically maintained by the provider and does not need to be written by itself. providers usually use _ ID as the primary key.

To obtain the id from the URI, you can call ContentUris. parseId ()Method.

Update

During the Update process, the system first queries based on the selection conditions and then changes the values.ContentValuesObject.

The method used isContentResolver. update ().

Delete

Delete is similar to query. Set selection conditions and find the row to be deleted. The client method returns the number of rows to be deleted.

The delete method is ContentResolver. delete ().

Pay attention to the malicious operations of users during update and deletion. For more information, 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.