Contentprovider and Uri

Source: Internet
Author: User

1. Use contentprovider to share data

The role of contentprovider in Android is to share data externally.In other words, you can share the data in the application to other applications through contentprovider, and other applications can use contentprovider to delete, modify, and query the data in your application. For data sharing, we have learned the file operation mode before. We know that the operation mode of a specified file is context. mode_world_readable or context. mode_world_writeable. So why use contentprovider to share data externally? If the file operation mode is used to share data externally, the Data Access Mode varies depending on the data storage mode, resulting in inconsistent data access methods, such: to use an XML file to share data externally, XML parsing is required to read data. To use sharedpreferences to share data, you must use the sharedpreferences API to read data.
The advantage of using contentprovider to share data externally is to unify the data access mode.
When an application needs to share data externally through contentprovider, the first step is to inherit contentprovider and override the following method:

 Public   Class  Personcontentprovider  Extends Contentprovider {
Public Boolean Oncreate ()
Public Uri insert (URI Uri, contentvalues values)
Public Int Delete (URI Uri, string selection, string [] selectionargs)
Public Int Update (URI Uri, contentvalues values, string selection, string [] selectionargs)
Public Cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder)
Public String GetType (URI)
}
Copy code

The second step must be in androidmanifest. XML uses <provider> to configure the contentprovider. To allow other applications to find the contentprovider, The contentprovider uses authorities (host name/Domain Name) to uniquely identify it, you can regard contentprovider as a website (think about it, the website also provides data), and authorities is its domain name:

 <  Manifest ....  >  
< Application Android: icon = "@ Drawable/icon" Android: Label = "@ String/app_name" >
< Provider Android: Name = ". Personcontentprovider"
Android: Authorities = "Com. ljq. providers. personprovider" />
</ Application >
</ Manifest >
Copy code

II. Introduction to Uri

Uri indicates the data to be operated, Uri mainly contains two parts of information: 1, The contentprovider to be operated, 2, the data in the contentprovider is operated, a URI consists of the following parts:

Contentprovider (content provider)'s scheme has been specified by Android, and scheme is: Content ://
The Host Name (or authority) is used to uniquely identify the contentprovider. External callers can find it based on this identifier..
Path can be used to indicate the data to be operated., The path should be built based on the business, as follows:
To operate records with the ID of 10 in the person table, you can build the path:/person/10.
Name field of the record whose ID is 10 in the person table to be operated, person/10/Name
To operate on all records in the person table, you can create a path like this:/person
To operate records in the xxx table, you can build the path:/xxx
Of course, the data to be operated may not come from the database, but also from other storage methods such as files, XML, or networks, as follows:
To operate on the Name node under the person node in the XML file, you can build the path:/person/Name
To convert a string to a URI, you can use the parse () method in the URI class as follows:
Uri uri = URI. parse ("content: // com. ljq. provider. personprovider/person ")

Iii. Introduction to the urimatcher class

Because URI represents the data to be operated, we often need to parse the URI and obtain data from the URI. The Android system provides two tool classes for Uri operations: urimatcher and contenturis. Understanding their usage will facilitate our development work.
The urimatcher class is used to match the URI.The usage is as follows:
The first step is to register all the URI paths you need, as shown below:

 //  Constant urimatcher. no_match indicates the return code that does not match any path.  
Urimatcher smatcher = New Urimatcher (urimatcher. no_match );
// If the match () method matches content: // Com. ljq. provider. personprovider/person path. The returned matching code is 1.
Smatcher. adduri ( " Com. ljq. provider. personprovider " , " Person " , 1 ); // Add the URI to be matched. If matched, the matching code is returned.
// If the match () method matches content: // Com. ljq. provider. personprovider/person/230 path, returns a matching code of 2
Smatcher. adduri ( " Com. ljq. provider. personprovider " , " Person /# " , 2 ); // # Wildcard
Switch (Smatcher. Match (URI. parse ( " Content: // com. ljq. provider. personprovider/person/10 " ))){
Case 1
Break ;
Case 2
Break ;
Default : // Mismatch
Break ;
}
Copy code

After registering the URI to be matched, you can use smatcher. the match (URI) method matches the input URI. If it matches, the matching code is returned. The matching code is the third parameter passed in by calling the adduri () method. Assume that it matches the content: // COM. ljq. provider. the path of personprovider/person. The returned matching code is 1.

Iv. usage of the contenturis class

The contenturis class is used to operate the ID section behind the URI path.It has two practical methods:
Withappendedid (Uri, ID) is used to add the ID part to the path:

 
Uri URI=Uri. parse ("Content: // com. ljq. provider. personprovider/person")
Uri resulturi=Contenturis. withappendedid (Uri,10);
//The generated URI is: content://Com. ljq. provider. personprovider/person/10
Copy code

The parseid (URI) method is used to obtain the ID part from the path:

Uri URI=Uri. parse ("Content: // com. ljq. provider. personprovider/person/10")
LongPersonid=Contenturis. parseid (URI );//The result is 10.
Copy code

5. Use contentprovider to share data

Main Methods of the contentprovider class:
Public Boolean oncreate (): This method is called after contentprovider is created. After Android is started, contentprovider is created only when other applications access it for the first time.
Public URI insert (URI Uri, contentvalues values): This method is used by external applications to add data to contentprovider.
Public int Delete (URI Uri, string selection, string [] selectionargs): This method is used by external applications to delete data from contentprovider.
Public int Update (URI Uri, contentvalues values, string selection, string [] selectionargs): This method is used by external applications to update data in contentprovider.
Public cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder): This method is used by external applications to obtain data from contentprovider.
Public String GetType (URI): This method is used to return the MIME type of the data represented by the current URL.

If the operated data belongsSet Type, The MIME type string should beVnd. Android. cursor. DIR/Start,

For example, to obtain all the person records, the URI is content: // COM. ljq. provider. personprovider/person, the returned mime-type string should be: "Vnd. android. cursor. DIR/person ".

If the data to be operated belongsNon-Set Data, The MIME type string should beVnd. Android. cursor. Item/Start,

For example, obtain the person record with the ID of 10. The URI is content: // COM. ljq. provider. personprovider/person/10, the returned MIME type string is: "Vnd. android. cursor. item/person ".

6. Use contentresolver to operate data in contentprovider

When an external application needs to add, delete, modify, and query data in contentprovider, you can use the contentresolver class to complete the operation. To obtain the contentresolver object, you can use getcontentresolver () provided by activity () method.The contentresolver class provides four methods for the same signature as the contentprovider class:
Public URI insert (URI Uri, contentvalues values): This method is used to add data to contentprovider.
Public int Delete (URI Uri, string selection, string [] selectionargs): This method is used to delete data from contentprovider.
Public int Update (URI Uri, contentvalues values, string selection, string [] selectionargs): This method is used to update data in contentprovider.
Public cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder): This method is used to obtain data from contentprovider.

The first parameter of these methods is Uri, which indicates the contentprovider to be operated and the data to be operated on,

Assume that Uri. parse ("content: // COM. ljq. providers. personprovider/person/10 "), the host name is com. ljq. providers. the contentprovider of personprovider performs operations. The operation data is a record with the ID of 10 in the person table.

Use contentresolver to add, delete, modify, and query data in contentprovider:

Contentresolver Resolver  =  Getcontentresolver ();
Uri URI = Uri. parse ( " Content: // com. ljq. provider. personprovider/person " );
// Add a record
Contentvalues values = New Contentvalues ();
Values. Put ( " Name " , " Linjiqin " );
Values. Put ( " Age " , 25 );
Resolver. insert (Uri, values );
// Retrieve all records in the person table
Cursor cursor = Resolver. Query (Uri, Null , Null , Null , " Personid DESC " );
While (Cursor. movetonext ()){
Log. I ( " Contenttest " , " Personid = " + Cursor. getint ( 0 ) + " , Name = " + Cursor. getstring ( 1 ));
}
// Change the name field value of the record with ID 1 to zhangsan.
Contentvalues updatevalues = New Contentvalues ();
Updatevalues. Put ( " Name " , " Zhangsan " );
Uri updateiduri = Contenturis. withappendedid (Uri, 2 );
Resolver. Update (updateiduri, updatevalues, Null , Null );
// Delete record with ID 2
Uri deleteiduri = Contenturis. withappendedid (Uri, 2 );
Resolver. Delete (deleteiduri, Null , Null );
Copy code

7. Monitor Data changes in contentprovider

If the visitor of contentprovider needs to know that the data in contentprovider has changed, call getcontentresolver () when the data in contentprovider changes (). notifychange (Uri, null) to notify visitors registered on this URI, for example:

Public ClassPersoncontentproviderExtendsContentprovider {
PublicUri insert (URI Uri, contentvalues values ){
DB. insert ("Person","Personid", Values );
Getcontext (). getcontentresolver (). policychange (Uri,Null);
}
}
Copy code

If the visitor of contentprovider needs to be notified of data changes, you must use contentobserver to listen to the data (the data is described in the URI). When the notification of data changes is received, the system will call the onchange () method of contentobserver:

 Getcontentresolver (). registercontentobserver (URI. parse (  "  Content: // com. ljq. providers. personprovider/person  "  ),
True , New Personobserver ( New Handler ()));
Public Class Personobserver Extends Contentobserver {
Public Personobserver (handler ){
Super (Handler );
}
Public Void Onchange ( Boolean Selfchange ){
// Here you can perform corresponding business processing
}< BR >}

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.