Interpreting Android ContentProvider (1) CRUD operations, androidcrud

Source: Internet
Author: User

Interpreting Android ContentProvider (1) CRUD operations, androidcrud

This article is translated from the official android documentation and tested by yourself.

Content providers can manage structured datasets, encapsulate data, and provide a data security mechanism. Content providers is a standard interface for cross-process data sharing. Chinese can be called the content provider.

When we want to obtain data from content providers, we can use the ContentResolver object to access the providers from the client. The ContentResolver object can communicate with the Content Provider instance, which is an instance that inherits a subclass of the ContentProvider class of the abstract class. Content Provider receives request data from the client (ContentResolver object), executes the request action, and returns the request result.

If we do not intend to share data with other applications, we do not need to create our own content provider. If you have such plans, you need to provide content provider to provide personalized query suggestions. At the same time, if you want to copy and paste complex data or files from your program to another program, we should also provide content provider.

The Android system also includes content providers for managing videos, audios, images, and contacts. Our applications can use these content providers when conditions are met.

Content Provider Basics

Content Provider is a part of android applications and provides a UI for interaction with data. However, content providers are mainly used by other programs. The providers and providers clients provide a consistent standard interface for data to process cross-process communication and secure access to data.

This section describes the following content:

  • Content provider operating mechanism.
  • APIS that can be used to access data through contentprovider.
  • The APIs that can be used in contentprovider.
  • Other APIs for convenient provider operations.

The following describes how to read the contact provider.

Overview

Content provider can expose data to other applications through one or more tables, which are similar to tables in relational databases. A row in the table represents a data record, and each column represents a type value of the record. This does not need to be described too much.

Note: The provider does not need to provide a primary key, but if you want to associate it with the ListView, you must provide a primary key named _ ID. The following is a detailed introduction.

Access provider

The application accesses data in the content provider through the abstract class ContentResovler object. The ContentResovler object and the ContentProvider object have the same name, and can perform CRUD (create, retrieve, update, and delete ).

The ContentResovler object in the client program process and the ContentProvider object in the program that owns the provider automatically process cross-process communication. The ContentProvider object is also used as an abstraction layer for external representations of datasets and data.

Of course, to access the system provider (usually a custom provider also needs to set a license), you must have a license (permissions ). The following is a detailed introduction.

For example, to query data in the provider table, we can callContentResolver.query()Then, this method will call ContentProvider to implement the Class Objectquery()Method. For example, the following code:

// Call the getContentResovler () method in the Activity to obtain the ContentResovler instance Cursor mCursor = getContentResovler (). query (uri, mProjection, // string array, which can be set to null, indicates reading all columns of mSelectionClause, // string constraints, can be set to null without the mSelectionArgs constraint, // string array, which is the specific value of the constraints, mSortOrder); // string

The returned Cursor object is described in detail below. The following table showsquery()How to match the parameters in the method with the SQL SELECT statement:

Parameters Corresponding SQL Section Description
Uri FROM table_name Queries the table_name table under an application.
MProjection Select column1, column2... Name of the column to be queried
MSelectionClause WHERE column1 = value Where constraints for query
MSelectionArgs - Provide values for placeholders in where
MSortOrder Order by column1, column2... Sort query results
Content URIs

The content URI creates a unique identifier for the data in the content provider. It consists of two parts: Permission and path. The permission is the provider name, which is used to differentiate the application provider. The path is the table name, which is used to distinguish different tables in the program. In this way, the content URI is formed. For example, the name of a provider is:com.sywyg.provider, A table name:table1. The final URI string is:content://com.sywyg.provider/table1. Wherecontent://Indicates that the URI is the content URI. After obtaining the URI string, you can use the following method to parse it into a Uri object:
Uri uri = Uri.parse("content://com.sywyg.provider/table1");

Most providers can access a single row by specifying the ID (for example, accessing the second row ):
Uri uri = ContentUris.withAppendedId("content://com.sywyg.provider/table1",2);

Note: The Uri and Uri. Builder classes can easily construct standard-format Uris using strings. The ContentUris class can easily add an id to the URI, for example, the preceding example.

Retrieve data from provider

This section describes how to retrieve data from the provider.

To facilitate the descriptionContentResolver.query()The query method is written in the UI thread, but in practice, asynchronous query should be performed in the Child thread. One of the methods to be implemented in the Child thread is to use the CursorLoader class (not sorted yet ). This part of the Loader under the activity in the official document is described in detail and has not been sorted out yet.

To retrieve data from the provider, follow these two steps:

Request permission

To search/query data, you must haveread accessLicense. We cannot set a license when the program is running. Therefore, you must specify this license in the manifest configuration file.<uses-permission>Label to set the permissions defined by the provider.
For example, if you want to obtain contact information, you can use the manifest file in our program:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Build query statement

After the permission is set in the previous step, we can query the tables in the provider. Through ContentResolver objectquery()Method setting specific query statements, as described abovequery().

Malicious Input Processing

Be careful with SQL injection when operating data. For example, enterquery()Parameters in the MethodmSelectionClauseSet:
String mSelectionClause = "var = " + mUserInput;
In this way, it may cause malicious SQL attacks, suchmUserInputIf it is assigned as '"nothing; drop table *;", the provider may delete all the tables.

Therefore, we should assign values to the constraints through placeholders. In this way, the values given by the Placeholders are only used as the query conditions and are not connected to SQL statements. For example, the preceding input can be in the following way:

String mSelectionClause =  "var = ?";String[] selectionArgs = {""};selectionArgs[0] = mUserInput;

Where, selectionArgs isquery().

Even if the provider does not rely on the SQL database, it is also possible to specify a placeholder.

Display query results

query()Method to return a Cursor object, so that we can read the query results from Cursor. The provider may restrict access to specific columns. Therefore, the access to specific columns may fail. Method In Cursor if the query result is nullgetCount()0. If an error occurs in the query, the result depends on a specific provider. Some may return null, and some may throw an exception.

Since Cursor is a row, it is a good choice to display data on ListView through SimpleCursorAdapter. To display it on ListView, the table must have an id column, which is retrieved by ListView. Therefore, providers usually need to provide the id column.

Obtain data from query results

We knowquery()Returns a Cursor object from which we can obtain the desired data. Use the Cursor movement method to traverse all rows of Cursor. The sample code is as follows:

// Determine the column number, that is, int index = mCursor. getColumnIndex ("column1");/** Only executes if the cursor is valid. * Run/if (mCursor! = Null) {/** Moves to the next row in the cursor. before the first movement in the cursor, the * "row pointer" is-1, and if you try to retrieve data at that position you will get an * exception. * move to the next row. The row number starts from-1. Therefore, the first row is moved to row 0th. */While (mCursor. moveToNext () {// read the data newWord = mCursor in the index column. getString (index); // Insert code here to process the retrieved word .... // end of while loop} mCursor. close ();} else {// Insert code here to report an error if the cursor is null or the provider threw an exception .}}

moveToNext()Method to move the cursor to the next line, and thengetXXX(int)You can get the value of the row of the corresponding column (is it like the usage of the Iterator of the Iterator ,,,,). Cursor has a seriesgetXXX(int)The method is used to return the corresponding values in the column (this type of value is used in the column). For examplegetString(). You can also usegetType()Returns the Data Type of a column. There are other CursorgetXXX()For examplegetColumnIndex("column1")Obtains the index of a specified column.

Permission)

The license specified by provider must be declared in the program that uses this provider. The license ensures that the user knows which data the program wants to obtain. If you do not set a license, the external program cannot use this provider. However, components in the same program as the provider can be obtained at will, even if licensed.

You can use 'To Set permissions in the manifest configuration file. During android installation, you must ensure that all licenses requested by the program are authorized; otherwise, the program cannot be installed.

Insert/update/delete data insert data

PassContentResolver.insert()Method To insert data to the table in the provider and return the URI of the inserted row. For example:

// Receives the insert return value Uri mNewUri; // The data to be inserted is stored in ContentValues (which is implemented by hashMap internally) ContentValues mNewValues = new ContentValues (); // sets the value of each column, the parameter is column and value mNewValues. put ("column1", "example"); // insert it to a table. The parameters are Uri and the inserted ContentValuesmNewUri = getContentResolver (). insert (uri, mNewValues );

You can use the ContentValues object to set the values in the table to be inserted. the type of the values set in this object does not need to be consistent with that in the actual column. If you do not want to set a column, you can useputNull("column2")Set this column to null. You do not need to specify a value for the id in the provider. This value is automatically added as the primary key.

Forinsert()The Uri format returned by the method is as follows:
Content: // authority/table/row id
This Uri can be used to access this row.ContentUris.parseId(uri)Obtain the id (that is, extract the last part of the uri with the id ).

Update Data

PassContentResolver.update()You can update the data. To clear the value, you only need to set it to null.

The simple code is as follows;

// Use ContentValues to set the updated data ContentValues mUpdateValues = new ContentValues (); // define the constraint and update the row whose column value is "example ..... String mSelectionClause = "column1 =? "; String [] mSelectionArgs = {" example "}; // receives the modified row. Int mRowsUpdated = 0; mUpdateValues. putNull ("column2"); mRowsUpdated = getContentResolver (). update (uri, mUpdateValues, mSelectionClause, mSelectionArgs );

update()The four parameters andquery()The first four parameters are the same.

Delete data

PassContentResolver.delete()You can delete data. This method receives three parameters: Uri, mSelectionClause, and mSelectionArgs. Andupdate()The parameter in the method is less than a ContentValues object.

The preceding CRUD statement is as follows:

  • Query: select * from table1 where range
  • Insert: insert into table1 (column1, column2) values (value1, value2)
  • Update: update table1 set column1 = value1 where range
  • Delete: delete from table1 where range
Data Type of Content Provider

Content Provider provides the following types:

  • Integer
  • Long integer (long)
  • Floating point
  • Long floating point (double)
  • Text

For other data types, the provider uses a 64 kB array BLOB (Binary Large OBject) to store data. BLOB is the field type used to store binary files in the database.

Provider also supports MIME data types, which are used to indicate the defined URIs. The following is a detailed description.

Other access provider forms

There are three optional access modes:

  • Batch access: Batch Processing
    You can use the ContentProviderOperation class to implement a group of accesses.ContentResolver.applyBatch()Operation.
  • Asynchronous Query
    You need to process data in another thread. You can use the CursorLoader object.
  • Access through intents
    Although you cannot directly send intent to the provider, you can send intent to the application where the provider is located. This is the best way to modify the provider data.

The following describes the Batch method and the intents method in detail. For Asynchronous queries, we will introduce them in the Loaders document of the Activity.

Batch access

Batch access is useful when you need to insert a large amount of row data or insert data into multiple tables.

You can use the ContentProviderOperation class to implement a group of accesses.ContentResolver.applyBatch()Operation.

For example, perform the following insert operations:

// Create a set of ContentProviderOperation objects. Each object represents a CRUD operation ArrayList <ContentProviderOperation> ops = new ArrayList <ContentProviderOperation> (); int rawContactInsertIndex = ops. size (); // use the build () method of the Builder class in the ContentProviderOperation class to create the ContentProviderOperation object. // if you remember correctly, this should be the Builder mode ops. add (ContentProviderOperation. newInsert (uri ). withValue ("column1", "value1 "). withValue ("column2", "value2 "). build (); getContentResolver (). applyBatch (authority, ops );
Access using intents

You can use Intent to indirectly access the content provider. Even without permission, we can use the result returned by Intent for indirect access.

Get temporary license

Without permission, we can send intent to another licensed program and return an intent object with URI permission. These specified URI licenses will exist until the authorized activity is destroyed. A program with a permanent license will authorize a temporary license by setting the flag attribute of intent:

  • Read Permission:FLAG_GRANT_READ_URI_PERMISSION
  • Write PermissionFLAG_GRANT_WRITE_URI_PERMISSION

Note that these flags are not read and write providers, but allow access to the URI itself.

Use helper app to display data

If our application is not licensed, we still want to display the data of another program through intent. For example, the calendar program receives an ACTION_VIEW intent to display the date or event. You do not need to create your own UI to display calendar information. The program that sends intent does not need to be associated with the provider Program.

The provider can be in the manifest File<provider>Tag attributes<android:grantUriPermission>You can also define a URI license.<provdier>Sub-tag<grant-uri-permission>.

For example, you can retrieve the contact data in the Contacts Provider, even if you do not have the READ_CONTACTS permission. Maybe we only need to read the information of a contact, so we do not need to request the READ_CONTACTS permission to access all contacts, so that users can choose which contact can be read by our program. Follow these steps:

Use another application

We can use another licensed application to operate the provider. For example, if you want to insert some events to the calendar, you can use the intent of ACTION_INSERT to start the calendar program and insert the calendar program.

MIME Type

MIME (Multipurpose Internet Mail Extensions) is an Internet standard that describes data types.
Content Providers can return standard MIME media types, custom MIME-type strings, or both.
MIME Type format:

type/subtype

For example, the well-known MIME types includetext/htmlThere are text and html subtypes.
A custom MIME-type string, also known as the "vendor-specific" MIME type, has more complex types and child types. For multiple rows, the type is usually:

vnd.android.cursor.dir

For a single row:

vnd.androi.cursor.item

The child type is specified by the provider, and the providers in android have some simple child types. For example, when creating a contact's phone number, you can use:

vnd.android.cursor.item/phone_v2

Here, the child type is phone_v2.

Other providers have custom child types, depending on the provider's permissions (autority) and path. For example, the permission is com. example. train2, including the Line1, Line2, and Line3 tables. For the uri of the Line1 table:
content://com.example.trains/Line1
The corresponding MIME type is:
vnd.android.cursor.dir/vnd.example.line1Orvnd.android.cursor.dir/vnd.com.example.train2.line1
For the 5th row URI of Line2:
content://com.example.trains/Line2/5
The corresponding MIME type is:
vnd.android.cursor.item/vnd.example.line2Orvnd.android.cursor.dir/vnd.com.example.train2.line2

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.