Android content provider-content providers (1)

Source: Internet
Author: User

Content providers is one of the four major Android components and plays a very important role. Read the official documentation to explain it:


Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. content providers are the standard interface that
Connects data in one process with code running in another process.


We can see that content providers are responsible for managing access to structured data. content providers encapsulate data and provide a set of data security mechanisms. Content providers is a set of interfaces for data access between different processes.

Content Providers provides a secure access mechanism for cross-process data access, which ensures reliable data organization and secure access.


In addition, let's take a look at how the official documentation explains the use of content providers:

When you want to access data in a content provider, you useContentresolverObject
In your application'sContextTo communicate with the provider as a client.ContentresolverObject
Communicates with the provider object, an instance of a class that implementsContentprovider. The provider object has es data
Requests from clients, performs the requested action, and returns the results.


This means that when you want to access data through content providers, you can use the contentresolver object in the context of the application to interact with the provider. The contentresolver object accesses the provider by implementing an instance of the abstract class contentprovider. The provider object receives data requests from the client, performs the request operation, and returns the request results.


Android uses content providers to manage data such as audio, video, images, and address book. You can also access the SQLite database through contentprovider. Let's take a look at the basic usage of content provider.


Prior to this, the official document provided some suggestions on whether to use content providers:

Decide if you need a content provider. You need to build a content provider if you want to provide one or more of the following features:

  • You want to offer complex data or files to other applications.
  • You want to allow users to copy complex data from your app into other apps.
  • You want to provide Custom Search suggestions using the search framework.


You need to use content providers in the following cases:

1. You want to provide complex data or files for other applications;

2. You want to allow users to copy complex data from your application to other applications.

3. You want to use the search framework to provide custom query recommendations


Content Provider accesses data through uri (Uniform Resource Locator). Uri can be understood as the unique address to access data. Uri consists of authority and data address, authority can be understood as the host address in the website address, while data address can be understood as the subaddress of a page. The two constitute a complete access address, the official document contains the following sentence: If your android package
Name isCom. example. <appname>, You shoshould give your provider the AuthorityCom. example. <appname>. Provider. It can be seen that authority naming is still normalized.

Uri format:Content: // <authority>/<path>/<ID>. path is the data path, for example, a table, and ID is the row where the primary key of this table is ID, it can also be understood as an object.


See the code for building content provider and using URI:

Publicclassexampleproviderextendscontentprovider {... // creates a urimatcher object. privatestaticfinalurimatcher surimatcher ;... /** the callto adduri () go here, for all of the content URI patterns that the provider * shoshould recognize. for this snippet, only the cballs for table 3 are shown. */... /** sets the integer value for multiple rows in Table 3 to 1. notice that no wildcard is used * in the path */surimatcher. adduri ("com. example. app. provider "," table3 ", 1);/** sets the code for a single row to 2. in this case, the "#" wildcard is * used. "content: // COM. example. app. provider/table3/3 "matches, but *" content: // COM. example. app. provider/table3 doesn' t. * The functions of the two Wildcards are described here. **: matches a string of any valid characters of any length. * #: matches a string of numeric characters of any length. */surimatcher. adduri ("com. example. app. provider "," table3/# ", 2 );... // implements contentprovider. query () publiccursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder ){... /** choose the table to query and a sort order based on the Code returned for the incoming * Uri. here, too, only the statements for table 3 are shown. */switch (surimatcher. match (URI) {// If the incoming Uri was for all of table3 case1: If (textutils. isempty (sortorder) sortorder = "_ id ASC"; break; // If the incoming Uri was for a single row case2:/** because this Uri was for a single row, the _ id value part is * present. get the last path segment from the URI; this is the _ id value. * Then, append the value to the WHERE clause for the query */selection = Selection + "_ id =" URI. getlastpathsegment (); break; default :... // If the URI is not recognized, you should do some error handling here .} // call the code to actually do the query}

After the abstract class contentprovider is implemented, there are several methods to be implemented:

Query ()

Retrieve data from your provider. Use the arguments to select the table to query, the rows and columns to return, and the sort order of the result. Return the data asCursorObject.

Insert ()

Insert a new row into your provider. Use the arguments to select the destination table and to get the column values to use. Return a content URI for the newly-inserted row.

Update ()

Update existing rows in your provider. Use the arguments to select the table and rows to update and to get the updated column values. Return the number of rows updated.

Delete ()

Delete rows from your provider. Use the arguments to select the table and the rows to delete. Return the number of rows deleted.

GetType ()

Return the MIME type corresponding to a content URI. This method is described in more detail in the sectionimplementing content
Provider MIME types.

Oncreate ()

Initialize your provider. The Android system CILS this method immediately after it creates your provider. notice that your provider is not created untilContentresolverObject
Tries to access it.

For example, if SQLite is used as the content provider data source, the following code snippet creates the maindatabasehelper subclass of sqliteopenhelper and generates the table main

// A string that defines the SQL statement for creating a tableprivatestaticfinalString SQL_CREATE_MAIN ="CREATE TABLE "+    "main "+                       // Table's name    "("+                           // The columns in the table    " _ID INTEGER PRIMARY KEY, "+    " WORD TEXT"    " FREQUENCY INTEGER "+    " LOCALE TEXT )";.../** * Helper class that actually creates and manages the provider's underlying data repository. */protectedstaticfinalclassMainDatabaseHelperextendsSQLiteOpenHelper{    /*     * Instantiates an open helper for the provider's SQLite data repository     * Do not do database creation and upgrade here.     */    MainDatabaseHelper(Context context){        super(context, DBNAME,null,1);    }    /*     * Creates the data repository. This is called when the provider attempts to open the     * repository and SQLite reports that it doesn't exist.     */    publicvoid onCreate(SQLiteDatabase db){        // Creates the main table        db.execSQL(SQL_CREATE_MAIN);    } }

Then define contentprovider to operate the database. In this way, an interface is established between the data source (SQLite) and the client (client ).

publicclassExampleProviderextendsContentProvider    /*     * Defines a handle to the database helper object. The MainDatabaseHelper class is defined     * in a following snippet.     */    privateMainDatabaseHelper mOpenHelper;    // Defines the database name    privatestaticfinalString DBNAME ="mydb";    // Holds the database object    privateSQLiteDatabase db;    publicboolean onCreate(){        /*         * Creates a new helper object. This method always returns quickly.         * Notice that the database itself isn't created or opened         * until SQLiteOpenHelper.getWritableDatabase is called         */        mOpenHelper =newSQLiteOpenHelper(            getContext(),        // the application context            DBNAME,              // the name of the database)            null,                // uses the default SQLite cursor            1                    // the version number        );        returntrue;    }    ...    // Implements the provider's insert method    publicCursor insert(Uri uri,ContentValues values){        // Insert code here to determine which table to open, handle error-checking, and so forth        /*         * Gets a writeable database. This will trigger its creation if it doesn't already exist.         *         */        db = mOpenHelper.getWritableDatabase();    } }

Briefly summarize some content providers:

1. content providers is one of the four main components in the Android system. It provides an access interface between the client and data source.

2. content providers can provide the cross-process data access function to expose local data to other applications for access.

3. To implement content providers, you only need to inherit the abstract class contentprovider and implement necessary abstract methods. To access contentprovider, you can access

The following is a brief introduction to contentprovider. The data source is the official Android documentation. If you have any shortcomings, please kindly advise.

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

To join our QQ group or public account, see: Ryan's
Zone public account and QQ Group

Welcome to my Sina Weibo: @ Tang Ren _ Ryan

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.