Android Content Provider

Source: Internet
Author: User

The Contentprovider mechanism in Android supports data storage and reading in multiple applications. This is the only way to share data across applications. In the android system, there is no public memory area for multiple applications to share and store data.

Android provides some main data types of ContentProvider, such as audio, video, images, and private address book. You can find some Contentprovider provided by android in the android. provider package. You can obtain these contentproviders and query the data they contain, provided that you have obtained the appropriate read permission.

If you want to disclose your data, you can use either of the following methods:

To create your own Contentprovider, you must inherit the ContentProvider class. If your data is consistent with the existing Contentprovider data structure, you can write the data to an existing Contentprovider, of course, the premise is to get the permission to write this Contentprovider. For example, add the member communication information in OA to the system's contact Contentprovider.

All contentproviders must implement the same interface to query Contentprovider and return data, including adding, modifying, and deleting data.

First, you need to obtain a ContentResolver instance. You can use the Activity member method getContentResovler:

 
 
  1. ContentResolver cr = getContentResolver(); 

The ContentResolver instance can find the specified Contentprovider and obtain the data of Contentprovider.

When the ContentResolver query process starts, the Android system will determine the specific Contentprovider required for the query and determine whether it starts and runs it. The android system initializes all contentproviders and does not need to be created by the user. In fact, none of the contentprovider users can directly access the contentprovider instance. They can only use ContentResolver to proxy in the middle.

Data Model

Contentprovider displays data similar to a single database table. Where:

Each row has a numeric field with a unique value, named _ ID, which can be used to locate the records in the table. The data structure returned by Contentprovider is a JDBC-like ResultSet. In android, is a Cursor object. URI

Each contentprovider defines a unique public URI to specify its dataset. A contentprovider can contain multiple datasets and can be considered as multiple tables. In this way, multiple Uris must correspond to each dataset. These Uris must begin with the following format:

Content ://

Indicates that this uri specifies a contentprovider.

If you want to create your own contentprovider, you 'd better set the custom URI to a constant of the class, which simplifies others' calls and will be easy to update the URI later. Android defines the CONTENT_URI constant for URI, for example:

android.provider.Contacts.Phones.CONTENT_URIandroid.provider.Contacts.Photos.CONTENT_URI

Note that Contacts in the preceding example is not supported in android 2.0 or later versions.

Query Contentprovider

To use a contentprovider, you need the following information:

Defines the Data Type of the fields returned by the contentprovider URI.

If you want to query the specific record rows of the contentprovider dataset), you also need to know the value of the Record ID.

Build Query

Query is the input of URI and other parameters, where URI is required and others are optional. If the system can find the contentprovider corresponding to the URI, a Cursor object is returned.

You can use ContentResolver. query () or Activity. managedQuery. The method parameters are the same, and the query process and return value are the same. The difference is that through Activity. the managedQuery () method not only obtains the Cursor object, but also manages the life cycle of the Cursor object. For example, when the Activity suspends pause, it unmounts the Cursor object, re-Query when Activity restart. You can also manage a Cursor object that is not in Activity management by calling Activity. startManaginCursor.

Similar to this:

 
 
  1. Cursor cur = managedQuery(myPerson, null, null, null, null); 

The first parameter myPerson is a Uri-type instance.

If you want to query records of a specified row, you need to use the _ ID value. For example, if the ID value is 23, the URI will be similar:

Content: //.../23

Android provides a convenient method, so developers do not need to splice the above URI, such:

 
 
  1. Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23); 

Or:

 
 
  1. Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23"); 

The difference between the two is that an ID value of the integer type is received, and a string type is received.

Other parameters:

Names, which can be null, indicates taking all the columns of the dataset, or declaring a String array, storing the column name in the array, such as: People. _ ID. Generally, the column names correspond to constants in the Contentprovider. For the filter of returned results, the format is similar to the WHERE clause in SQL. The difference is that the WHERE keyword is not included. If null is returned, it indicates no filtering, for example, name = ?; The parameter of the preceding filter is a String array, which is used in the preceding condition? The placeholder value. The sorting parameter is similar to the order by clause in SQL. However, you do not need to write the ORDER BY clause, such as name desc. If it is not sorted, enter null.

The returned value is a Cursor object. The Cursor is located before the first record.

The following example applies to android 2.0 and later versions. You can obtain the name field from the android address book:

 
 
  1. Cursor cursor = getContentResolver().query( 
  2.         ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null,null); 

Returned content

The returned values are similar. Different contentproviders have different columns and names, but there are two identical columns. the one mentioned above is _ ID, which is used to uniquely identify a record, there is also a _ COUNT used to record the size of the entire result set. We can see that the value of _ COUNT in the figure above is the same.

Read the returned data

If ID is used during query, only one record is returned. In other cases, there are usually multiple records. Similar to the JDBC ResultSet, You need to manipulate the cursor to traverse the result set. In each row, you can obtain the column value through the column name. You can use getString (), getInt (), getFloat (). For example:

 
 
  1. while (cursor.moveToNext()) { 
  2.     builder 
  3.             .append( 
  4.                     cursor 
  5.                             .getString(cursor 
  6.                                     .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))) 
  7.             .append("-"); 

Different from JDBC, you cannot directly obtain the column value through the column name. You can only first obtain the integer index value of the column by the column name, and then locate and obtain the column value through the index value.

Edit data

You can use contentprovider to implement the following editing functions:

Add new records, add new values to existing records, update existing records in batches, and delete records.

All editing functions are implemented through ContentResolver. Some contentproviders have stricter requirements on permissions and need write permissions. If they do not, an error is reported.

Add record

To add a record to contentprovider, first set a map-like key-value pair in the ContentValues object. Here, the key value corresponds to the column name and key-Value Pair value in contentprovider, is The expected type of the corresponding column. Then, call the ContentResolver. insert () method to pass in the ContentValues object and the URI of the corresponding Contentprovider. The returned value is the URI object of the new record. In this way, you can use this URI to obtain the Cursor object containing this record. For example:

 
 
  1. ContentValues values = new ContentValues(); 
  2.  
  3. values.put(People.NAME, "Abraham Lincoln"); 
  4.  
  5. Uri uri = getContentResolver().insert(People.CONTENT_URI, values); 
Add value to original records

If a record already exists, you can add a new value to the record or edit an existing value.

First, you must go to the original value object, and then clear the original value, and then add the record as above:

 
 
  1. Uri uri=Uri.withAppendedPath(People.CONTENT_URI, "23"); 
  2.  
  3. Uri phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); 
  4.  
  5. values.clear(); 
  6. values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE); 
  7. values.put(People.Phones.NUMBER, "1233214567"); 
  8. getContentResolver().insert(phoneUri, values); 
Batch update Value

Update the values of a group of records in batches. For example, NY is renamed Eew York. You can call the ContenResolver. update () method.

Delete record

To delete a single record, call the ContentResolver. delete () method and specify the URI parameter to a specific row.

To delete multiple records, call the ContentResolver. delete () method. The URI parameter specifies the Contentprovider and carries a WHERE clause condition similar to SQL. This is similar to the above, without the WHERE keyword.

Create your own Contentprovider

To create contentprovider, you must:

Set the storage system. Most contentproviders use files or SQLite databases, but you can store data in any way. Android provides SQLiteoOpenHelper to help developers create and manage SQLiteDatabase. Inherits ContentProvider and provides access to data. Declare contentprovider in the manifest file. Inherit ContentProvider class

You must define a subclass of the ContentProvider class and implement the following methods:

query()insert()update()delete()getType()onCreate()

Query () method. The returned value is the Cursor instance used to iterate the request data. Cursor is an interface. Android provides some read-only and JDBC resultsets for this interface, and the latter also provides the optional write feature) Cursor implementation. For example, SQLiteCursor can iterate data in the SQLite database. You can obtain the Cursor instance through the query () method of the SQLiteDatabase class. There are other Cursor implementations, such as MatrixCursor, used when data is not stored in the database.

Because Contentprovider may be called by multiple ContentResolver objects in different processes and threads, thread security must be considered for implementing Contentprovider.

As a good habit, in code that implements data editing, call the ContentResolver. policychange () method to notify listeners that listen for data changes.

When implementing subclass, there are still some steps to simplify the use of the Contentprovider client:

Defines a public static final Uri constant named CONTENT_URI:

 
 
  1. public static final UriCONTENT_URI = 
  2.                Uri.parse("content://com.example.codelab.transportationprovider"); 

If there are multiple tables, they also use the same CONTENT_URI, but their paths are different.

That is to say, the red frame is consistent.

Defines the returned column name, public static final, and column name value. For example, the SQLite database is used as the storage, and the column name of the corresponding table is defined.

In this document, you need to write the Data Types of each column for easy reading.

If you want to process the new MIME data type, such as using Intent and mimeType with data, you need. getType () method. For more information, see compile a complete Contentprovider example to compile a getType method section.

If the processing of large data in a database table, such as a large bitmap file, is usually stored in a file system, you can refer to the use of large binary files in contentprovider, so that third-party contentprovider users, attackers can access files that do not have the permission to use contentprovider as a proxy.

Declare ContentProvider

After creating a ContentProvider, you must declare it in the manifest file so that the android system can know it. Only when other applications need to call this ContentProvider can they be created or called.

The syntax is similar:

 
 
  1. <provider android:name="com.easymorse.cp.MyContentProvider"  
  2.           android:authorities="com.easymorse.cp.mycp"></provider>  

Android: name indicates the full name of the ContentProvider inheritance class.

Android: authorities to write and CONTENT_URI constant part B is shown in the figure above ).

Do not add C and D to authorities. Authorities are used to identify ContentProvider. C and D are actually used internally by ContentProvider.

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.