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 use theContentResolver object in your application's Context to communicate with the provider as a client. the ContentResolverobject communicates with the provider object, an instance of a class that implements ContentProvider. the provider object names 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 authority com. example. <appname>. provider. it can be seen that authority naming is still normalized.
For URI format: content: // <authority>/<path>/<id>, path is the data path, for example, a table, id is the row in which 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:
[Java]
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 callfor 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,
* "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 as a Cursor object.
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 until a ContentResolver object 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
[Java]
// 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
* Repository and SQLite reports that it doesn't exist.
*/
Publicvoid onCreate (SQLiteDatabase db ){
 
// Creates the main table
Db.exe cSQL (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 ).
[Java]
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: www.2cto.com
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


Author: tangren03

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.