Usage of Android Content Provider

Source: Internet
Author: User

Content Provider:A component must be placed under the main package or sub-package of the application;

The component configuration needs to be configured in the configuration file; the content provider needs to be configured in the application node;
What is the role of content providers in applications?Share Data externally(Any type of data), Other programs can perform CRUD on the data, such as the address book;
If data is shared externally by using files, different types of files require different api access methods, resulting in complicated access. The content provider provides a unified api for data operations;
<Provider
Android: name = ". PersonProvider" <! -- Name of the content provider class -->
Android: authorities = "cn. wordtech. providers. personprovider"

Android:Exported= "False"> <! -- Solve android Permission Denial error !, This item needs to be configured when the data of the listener content provider changes -->
</Provider>

In addition:
Android: authorities: Specifies a unique identifier for the content provider so that other applications can obtain this provider only;

UriIndicates the data to be operated;
Uri mainly contains two parts of information: 1> ContentProvider to be operated, 2> what data in ContentProvider is operated

ContentProvider(Content provider) the scheme has been specified by Android, and the scheme is: content ://
The Host Name (or Authority) uniquely identifies this ContentProvider. An external caller can locate it based on this identifier,
The path can be used to indicate the data we want to operate on. The path construction depends on the business.
Ex:
To operate records with the id of 10 in the person table, you can build the path:/person/10.
To operate on the name field of the record with the id of 10 in the person table, you can build the following path:/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
The data to be operated may not be files in the database, but also files, xml, or network.
Ex:
To operate on the name node under the person node in the xml file, you can build the path:/person/name

Copy codeThe Code is as follows: public class PersonProvider extends ContentProvider {// Content Provider must inherit from the ContentProvider class
// There are two situations in the deletion and modification query:
// Person performs operations on the entire table
// Person/id
Private DBOpenHelper dbOpenHelper;
Private static final UriMatcher MATCHER = new UriMatcher (UriMatcher. NO_MATCH); // new UriMatcher (code); code indicates the value returned when the matching fails;
Private static final int PERSONS = 1;
Private static final int PERSON = 2;
// Set matching items
Static {
MATCHER. addURI ("cn. wordtech. providers. personprovider", "person", PERSONS );
MATCHER. addURI ("cn. wordtech. providers. personprovider", "person/#", PERSON); // # indicates a number
}
// Content: // cn. wordtech. providers. personprovider/person
@ Override
Public boolean onCreate (){
// Called by the system. The ContentProvider is called when the ContentProvider instance is created. After Android is started, the ContentProvider is created when an application accesses ContentProvider for the first time;
DbOpenHelper = new DBOpenHelper (getContext (), 1 );
Return false;
}

// The data can be queried by external applications and the queried cursor object is returned.
@ Override
Public Cursor query (Uri uri, String [] projection, String selection,
String [] selectionArgs, String sortOrder ){
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
Switch (MATCHER. match (uri )){
Case 1:
Return db. query ("person", projection, selection, selectionArgs,
Null, null, sortOrder );
Case 2:
Long rowid = ContentUris. parseId (uri); // return the id of the operation
String where = "personid =" + rowid;
If (selection! = Null &&! "". Equals (selection. trim ())){
Where + = "and" + selection;
}
Return db. query ("person", projection, where, selectionArgs, null,
Null, sortOrder );

Default:
Throw new IllegalArgumentException ("");
}
}

// This method is used to return the MIME type of the data represented by the current Uri,
// If the operated data belongs to the set type, the MIME string starts with "vnd. android. cursor. dir"
// If the operated data belongs to a non-set type, the MIME string starts with "vnd. android. cursor. item"
@ Override
Public String getType (Uri uri ){
Switch (MATCHER. match (uri )){
Case 1:
Return "vnd. android. cursor. dir/person ";
Case 2:
Return "vnd. android. cursor. item/person ";
Default:
Throw new IllegalArgumentException ("");
}
}

// This method needs to return the Uri corresponding to the operation record
@ Override
Public Uri insert (Uri uri, ContentValues values ){
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
Switch (MATCHER. match (uri )){
Case 1:
Long rowid = db. insert ("person", "", values); // return the row number? Primary Key Value
// Uri insertUri = Uri
//. Parse ("content: // com. sqlite. PersonProvider/person /"
// + Rowid );
Uri insertUri = ContentUris. withAppendedId (uri, rowid );
Return insertUri;
Default:
Throw new IllegalArgumentException ("this is Unknow Uri:" + uri );
}

}

// Returns the number of affected rows.
@ Override
Public int delete (Uri uri, String selection, String [] selectionArgs ){
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
Int num = 0;
Switch (MATCHER. match (uri )){
Case 1:
Num = db. delete ("person", selection, selectionArgs); // clear the entire table
Break;
Case 2:
Long rowid = ContentUris. parseId (uri); // return the id of the operation
String where = "personid =" + rowid;
If (selection! = Null &&! "". Equals (selection. trim ())){
Where + = "and" + selection;
}
Num = db. delete ("person", where, selectionArgs );
Break;
Default:
Throw new IllegalArgumentException ("");
}
Return num;
}

@ Override // returns the number of affected rows
Public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs ){
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
Int num = 0;
Switch (MATCHER. match (uri )){
Case 1:
Num = db. update ("person", values, selection, selectionArgs );
Break;
Case 2:
Long rowid = ContentUris. parseId (uri); // return the id of the operation
String where = "personid =" + rowid;
If (selection! = Null &&! "". Equals (selection. trim ())){
Where + = "and" + selection;
}
Num = db. update ("person", values, where, selectionArgs );
Break;
Default:
Throw new IllegalArgumentException ("");
}
Return num;
}
}

The following is a test of the previous class.
Copy codeThe Code is as follows: public class AccessContentProviderTest extends AndroidTestCase {
Public void testinsert (){
Uri uri = Uri. parse ("content: // cn. wordtech. providers. personprovider/person"); // obtain the content provider based on the Identification name
ContentResolver cr = this. getContext (). getContentResolver (); // This class provides applications access to the content model
ContentValues values = new ContentValues ();
Values. put ("name", "Livingstone ");
Value. put ("phone", "110 ");
Values. put ("amount", "1111111111 ");
Cr. insert (uri, values); // The value of the content provider is called within the cr;
}

Public void testdelete (){
Uri uri = Uri. parse ("content: // cn. wordtech. providers. personprovider/person/1"); // obtain the content provider based on the Identification name
ContentResolver cr = this. getContext (). getContentResolver ();
Cr. delete (uri, null, null );
}

Public void testupdate (){
Uri uri = Uri. parse ("content: // cn. wordtech. providers. personprovider/person/2"); // obtain the content provider based on the Identification name
ContentResolver cr = this. getContext (). getContentResolver ();
ContentValues values = new ContentValues ();
Values. put ("name", "Livingstone11 ");
Cr. update (uri, values, null, null );
}

Public void testquery (){
Uri uri = Uri. parse ("content: // cn. wordtech. providers. personprovider/person"); // obtain the content provider based on the Identification name
ContentResolver cr = this. getContext (). getContentResolver ();
Cursor cursor = cr. query (uri, null, "personid asc ");
While (cursor. moveToNext ()){
String name = cursor. getString (cursor. getColumnIndex ("name "));
Log. I ("Name", name );
}
}
}

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.