Explanation of Content Provider 2

Source: Internet
Author: User

Modify data
You can modify the data saved by the content provider as follows:
1. Add a new record;
2. Add new values for existing data;
3. update existing records in batches;
4. delete records
All data modification operations can be completed through the ContentResolver method. Some content providers require more permissions to modify data than to read data. If you do not have the permission to modify the content provider data, the ContentResolver method becomes invalid.
Add record
To add a new record to the content provider, first set the key-value pair in the ContentValues object, and the set key corresponds to the column name in the content provider, and the value content is the value we want to set for the new record. Then, call the ContentResolver. insert () method, and pass the content provider to be processed and the configured ContentValues key-value pair to this method as a parameter. This method returns the complete URI of the new record -- that is, the URI of the provider to be operated plus the ID number appended to the new record. Then, you can use this complete URI to perform query operations, obtain a Cursor pointing to this new record, and use this obtained Cursor to perform subsequent modification record operations. For example:
Import android. provider. Contacts. People;
Import android. content. ContentResolver;
Import android. content. ContentValues;
 
 
ContentValues values = new ContentValues ();
 
 
// Add Abraham Lincoln to contacts and make him a favorite.
Values. put (People. NAME, "Abraham Lincoln ");
// 1 = the new contact is added to favorites
// 0 = the new contact is not added to favorites
Values. put (People. STARRED, 1 );
 
 
Uri uri = getContentResolver (). insert (People. CONTENT_URI, values );
Import android. provider. Contacts. People;
Import android. content. ContentResolver;
Import android. content. ContentValues;


ContentValues values = new ContentValues ();


// Add Abraham Lincoln to contacts and make him a favorite.
Values. put (People. NAME, "Abraham Lincoln ");
// 1 = the new contact is added to favorites
// 0 = the new contact is not added to favorites
Values. put (People. STARRED, 1 );


Uri uri = getContentResolver (). insert (People. CONTENT_URI, values); add a new value
If a record already exists, you can add new information to it or modify existing information. For example, the next step in the preceding example is to add a new contact information, such as a phone number, an IM account, or an email address, to a new entry.
The best way to add a new record to the Contacts database is to append the table name to the URI that stores the new record, and then add the new data value with the modified URI. Each Contacts table exposes a constant named CONTENT_DIRECTORY. The following Code goes on to add a phone number and an email address for the newly created record.
Uri phoneUri = null;
Uri emailUri = null;
 
 
// Add a phone number for Abraham Lincoln. Begin with the URI
// The new record just returned by insert (); it ends with the _ ID
// Of the new record, so we don't have to add the ID ourselves.
// Then append the designation for the phone table to this URI,
// And use the resulting URI to insert the phone number.
PhoneUri = Uri. withAppendedPath (uri, People. Phones. CONTENT_DIRECTORY );
 
 
Values. clear ();
Values. put (People. Phones. TYPE, People. Phones. TYPE_MOBILE );
Values. put (People. Phones. NUMBER, "1233214567 ");
GetContentResolver (). insert (phoneUri, values );
 
 
// Now add an email address in the same way.
EmailUri = Uri. withAppendedPath (uri, People. ContactMethods. CONTENT_DIRECTORY );
 
 
Values. clear ();
// ContactMethods. KIND is used to distinguish different kinds
// Contact methods, such as email, IM, etc.
Values. put (People. ContactMethods. KIND, Contacts. KIND_EMAIL );
Values. put (People. ContactMethods. DATA, "test@example.com ");
Values. put (People. ContactMethods. TYPE, People. ContactMethods. TYPE_HOME );
GetContentResolver (). insert (emailUri, values );
Uri phoneUri = null;
Uri emailUri = null;


// Add a phone number for Abraham Lincoln. Begin with the URI
// The new record just returned by insert (); it ends with the _ ID
// Of the new record, so we don't have to add the ID ourselves.
// Then append the designation for the phone table to this URI,
// And use the resulting URI to insert the phone number.
PhoneUri = Uri. withAppendedPath (uri, People. Phones. CONTENT_DIRECTORY );


Values. clear ();
Values. put (People. Phones. TYPE, People. Phones. TYPE_MOBILE );
Values. put (People. Phones. NUMBER, "1233214567 ");
GetContentResolver (). insert (phoneUri, values );


// Now add an email address in the same way.
EmailUri = Uri. withAppendedPath (uri, People. ContactMethods. CONTENT_DIRECTORY );


Values. clear ();
// ContactMethods. KIND is used to distinguish different kinds
// Contact methods, such as email, IM, etc.
Values. put (People. ContactMethods. KIND, Contacts. KIND_EMAIL );
Values. put (People. ContactMethods. DATA, "test@example.com ");
Values. put (People. ContactMethods. TYPE, People. ContactMethods. TYPE_HOME );
GetContentResolver (). insert (emailUri, values );

You can add a small amount of binary data to the table by calling ContentValues. put. For example, this method is very effective for small icon-type images and Short audio files. However, if you have large binary data to be added, such as an image file and a complete song, the data to be added is a content: URI and ContentResolver is called. openOutputStream () method, and the URI of this file serves as the parameter of this method. (This will enable the content provider to store the data using a file and record the file path in an implicit domain of this record)
In this regard, MediaStore content provider is independent of the main provider of image, audio, and video files, which provides a convenience: We can use query () and managedQuery () the same URI is used to obtain information about binary data (for example, captured images). We can use the openInputStream () method and the obtained binary data to obtain the binary data, the following code shows the convenience:
Import android. provider. MediaStore. Images. Media;
Import android. content. ContentValues;
Import java. io. OutputStream;
 
 
// Save the name and description of an image in a ContentValues map.
ContentValues values = new ContentValues (3 );
Values. put (Media. DISPLAY_NAME, "road_trip_1 ");
Values. put (Media. DESCRIPTION, "Day 1, trip to Los Angeles ");
Values. put (Media. MIME_TYPE, "image/jpeg ");
 
 
// Add a new record without the bitmap, but with the values just set.
// Insert () returns the URI of the new record.
Uri uri = getContentResolver (). insert (Media. EXTERNAL_CONTENT_URI, values );
 
 
// Now get a handle to the file for that record, and save the data into it.
// Here, sourceBitmap is a Bitmap object representing the file to save to the database.
Try {
OutputStream outStream = getContentResolver (). openOutputStream (uri );
SourceBitmap. compress (Bitmap. CompressFormat. JPEG, 50, outStream );
OutStream. close ();
} Catch (Exception e ){
Log. e (TAG, "exception while writing image", e );
}
Import android. provider. MediaStore. Images. Media;
Import android. content. ContentValues;
Import java. io. OutputStream;


// Save the name and description of an image in a ContentValues map.
ContentValues values = new ContentValues (3 );
Values. put (Media. DISPLAY_NAME, "road_trip_1 ");
Values. put (Media. DESCRIPTION, "Day 1, trip to Los Angeles ");
Values. put (Media. MIME_TYPE, "image/jpeg ");


// Add a new record without the bitmap, but with the values just set.
// Insert () returns the URI of the new record.
Uri uri = getContentResolver (). insert (Media. EXTERNAL_CONTENT_URI, values );


// Now get a handle to the file for that record, and save the data into it.
// Here, sourceBitmap is a Bitmap object representing the file to save to the database.
Try {
OutputStream outStream = getContentResolver (). openOutputStream (uri );
SourceBitmap. compress (Bitmap. CompressFormat. JPEG, 50, outStream );
OutStream. close ();
} Catch (Exception e ){
Log. e (TAG, "exception while writing image", e );
} Batch update data
Update a group of records in batches (for example, change "New York" of all domains to "NY "). Call the ContentResolver. update () method. The columns and values to be modified are used as parameters.
Delete a record
To delete a single record, use the URI of a special row as the parameter and call ContentResolver. delete () to delete the record.
To delete multiple rows (multiple records), use the data type URI of the record to be deleted and the SQL WHERE statement that defines the row to be deleted as the parameter to call ContentResolver. delete () method (for example, android. provider. contacts. people. CONTENT_URI ). (Note: If you want to delete a general type, make sure that it contains a correct WHERE statement, otherwise, you will delete more records than you imagined ).
Create a Content Provider
To create a content provider, you must:
1. Set up a data storage system. Most content providers use the file storage method of the Android system or the SQLite database to store the data, but you can store your own data in any way. Android provides the SQLiteOpenHelper class to help you create databases and manage databases.
2. Extend the ContentProvider class to provide data storage methods
3. Declare your content provider in the ANndroidManifest. xml file of your application.
Extended ContentProvider class
You can define a ContentProvider subclass to expose your data to objects that use the data through ContentResolver and Cursor objects. In principle, this also means implementing six abstract methods defined in the ContentProvider class:
Query ()
Insert ()
Update ()
Delete ()
GetType ()
OnCreate ()
The query () method must return a Cursor object through which the requested data can be operated. Cursor is an interface, but Android provides some defined Cursor objects for direct use. For example, SQLiteCursor can operate data stored in the SQLite database. You can use the query () method of the SQLiteDatabase class to obtain the Cursor object. Here are some other Cursor implementations-for example, MatrixCursor-for those data that are no longer stored in the database.
Because these ContentProvider methods can be called by ContentResolver objects in multiple processes and threads, they must be implemented in a thread-safe way.
Out of courtesy, you may want to notify the listener or user by calling ContentResolver. policychange () when the data is modified.
In addition to defining a subclass, you can perform the following steps to simplify client programming and make this class more effective:
1. Define a public static final Uri named CONTENT_URI. This is the complete content: URI string of the data to be processed by your content provider.
You must define a unique value for this string constant. The best way is to use the class name (lower case) completed by the content provider ). therefore, for a Transpotation class, we can define it as follows: public static final Uri CONTENT_URI = Uri. parse ("content: // com. example. codelab. transportationprovider ");
Public static final Uri CONTENT_URI = Uri. parse ("content: // com. example. codelab. transportationprovider "); if this provider contains sub-tables, you also need to define the CONTENT_URI constant for each sub-Table. These Sub-tables have the same permissions (that is, the content provider identifier ), and these sub-tables are only distinguished by their paths, as shown in the following example:
Content: // com. example. codelab. transportationprovider/train
Content: // com. example. codelab. transportationprovider/air/domestic
Content: // com. example. codelab. transportationprovider/air/international
Content: // com. example. codelab. transportationprovider/train
Content: // com. example. codelab. transportationprovider/air/domestic
Content: // com. example. codelab. transportationprovider/air/international introduces content: URI in detail.
2. Define the column name of the content provider to return to the client.
3. Carefully record the data type of each column of data. The client needs this information to read the data.
4. If you want to process a new data type, you must define a new MIME type as the return value of your COntentProvider. getType () method.
5. If you want to add too much data to the table-a file representing a large Bitmap-the field that exposes data to the client must contain a content: URI string.
Define a content provider.
To let the system know your own defined content provider, you should use the <provider> label in the AndroidManifest file for definition. Content Providers not defined here are invisible to the system.
<Provider> the name attribute of a tag is the full name of the Conprovider subclass. The authotities attribute is the content: URI permission section of the provider. For example, if the name of the ContentProvider subclass is AutoInfoProvider, the <provider> element may be defined as follows:
<Provider android: name = "com. example. autos. AutoInfoProvider"
Android: authorities = "com. example. autos. autoinfoprovider"
.../>
/Provider>
<Provider android: name = "com. example. autos. AutoInfoProvider"
Android: authorities = "com. example. autos. autoinfoprovider"
.../>
</Provider> note that the authorities attribute ignores the content: URI path. For example, if AutoINfoProvider has sub-tables for different types of autos or manufacturers, content: // com. example. autos. autoinfoprovider/honda
Content: // com. example. autos. autoinfoprovider/gm/compact
Content: // com. example. autos. autoinfoprovider/gm/suv
Content: // com. example. autos. autoinfoprovider/honda
Content: // com. example. autos. autoinfoprovider/gm/compact
Content: // com. example. autos. autoinfoprovider/gm/suv paths should not be declared in the AndroidManifest file. Because the permission is for the provider, rather than for the path; your provider should be able to explain the URL Information in its own way.
Other properties of <provider> can be used to set the permission to read and rewrite data, provide an icon and a message displayed to the user, enable and disable the provider, and so on. If the data in content provider does not need to be synchronized among multiple processes, set the multiprocess attribute to "true ". This allows every client process to instantiate This provider and establish the necessary IPC.
Content URI Summary
The following is an overview of an important part of content URI:

 

A. The standard prefix indicates that the data is held by the content provider. This will never need to be modified.
B. The part of the URI. It is used to identify a content provider. For third-party applications, this must be the full name of the class (in lower case) to ensure that it is unique. Which defines the authorities attribute of the <provider> element: <provider android: name = ". TransportationProvider"
Android: authorities = "com. example. transportationprovider"
...>
<Provider android: name = ". TransportationProvider"
Android: authorities = "com. example. transportationprovider"
...> C. This part is used by the content provider to determine which types of data are requested. This can be empty or long. If a content provider only exposes one type of data (for example, only the trains type), it can be empty. If a content provider exposes several types of data, including child data, it may have several segments that are so long-for example: the four possible types are land/bus, labd/train, sea/ship, and sea/submarine.

D. the ID of the special record to be queried. If yes, this is the _ ID value recorded by the request. If the request is not for a single record, the segment and slash will be ignored:


Content: // com. example. transportationprovider/trains
Content: // com. example. transportationprovider/trains

From the column chenlong12580


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.