Implementation method of ContentProvider data sharing in Android

Source: Internet
Author: User
Tags sqlite sqlite database

Then we can also define our own ContentProvider to share the data across applications. Data can be stored in a specific way for databases, files, or other forms of persistent or non-persistent storage. Here we still use the SQLite database storage data.

The old rules, first a little basic knowledge.

A Basic knowledge

What is 1:uri? A Uniform resource identifier used to identify a resource.

Usually a URI consists mainly of three parts: scheme, authority, path
1.scheme:contentprovider (content Provider) scheme has been defined by the Android system as: content://
2. Host name (or authority): used to uniquely identify this contentprovider, the external caller can find it based on this identity.
3. Path: can be used to represent the data we want to operate, the path should be built according to the business, as follows:
To manipulate a record with ID 5 in the Persion table, you can build such a path:/PERSION/5
To manipulate the name field of a record with ID 20 in the persion table, PERSION/NAME/10
To manipulate all the records in the Persion table, you can build such a path:/persion
Gets Uri:uri uri = Uri.parse ("content://com.dongzi/persion") using the Parse () method in the Uri class

The scheme:content://of the URI above

Authority:com.dongzi

Path:/contact


2, Urimatcher, Contenturist and Contentresolver

The Android system provides two tool classes for manipulating URIs: Urimatcher and Contenturis

Urimatcher: For matching URIs:

The code is as follows Copy Code
static final int codes=2;


static final int code=1;


Static final String authority= "Com.dongzi"; Authorized


Static final Urimatcher Urimatcher; URI Matching


static {//Registration matching URI and return code


Urimatcher=new Urimatcher (Urimatcher.no_match); Do not match any path return-1


Urimatcher.adduri (Authority, "Persion", codes); Match Content://com.dongzi/persion return 2


Urimatcher.adduri (Authority, "persion/#", CODE); Match content://com.dongzi/persion/1234 return 1


}


Contenturis: Used to get the ID part behind the URI path, which has two more practical methods:
Withappendedid (URI, id) is used to add the ID portion to the path
The Parseid (URI) method is used to get the ID part from the path

  code is as follows copy code
//Add ID for URI
        Uri uri=uri.parse ("content://" +authority+ "/persion");
        Contenturis.withappendedid (URI, 1234);
       //generated URI is: content://com.dongzi/person/1234
        
       //Get ID after URI
         Long Id=contenturis.parseid (Uri.parse ("content://com.dongzi/person/1234"));
       //Get ID: 1234

Contentresolver provides the following main methods:

The code is as follows Copy Code

@Override


public int Delete (Uri arg0, String arg1, string[] arg2) {


This method is used for external applications to delete data from ContentProvider.


return 0;


}


@Override


Public String GetType (Uri uri) {


This method is used to return the MIME type of the data represented by the current URL.


return null;


}


@Override


Public URI insert (URI uri, contentvalues values) {


This method is used for external applications to add data to ContentProvider.


return null;


}


@Override


public Boolean onCreate () {


is created the first time another application accesses it.


return false;


}


@Override


Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {


This method is used for external applications to obtain data from ContentProvider.


return null;


}


@Override


public int update (URI uri, contentvalues values, String selection, string[] Selectionargs) {


This method is used for external applications to update data in ContentProvider.


return 0;


}

The main point here is the MIME type of the data represented by the URL:

If the operation's data belongs to the collection type, then the MIME type string should start with vnd.android.cursor.dir/,

For example, to get the URI of all person records to be Content://com.dongzi/person, the MIME type string returned should be: "Vnd.android.cursor.dir/person".

If the data to be manipulated belongs to a vnd.android.cursor.item/type of data, then the MIME type string should start with the

For example: Get a person record with ID 1234, URI is content://com.dongzi/person/1234, then the MIME type string returned is: "Vnd.android.cursor.item/person".

Using Contentresolver to manipulate data in ContentProvider

When an external application needs to add, delete, modify, and query the data in the ContentProvider, you can use the Contentresolver class to get the Contentresolver object. You can use the Getcontentresolver () method provided by the activity. Contentresolver provides a contentprovider corresponding to the increase, delete, change, check method.

Monitor the change of data in ContentProvider

If we need to get a data change notification, you can use Contentobserver to notify changes and monitor the data (data using a URI description).

The code is as follows Copy Code

Notify the content and change, while registering content monitoring, monitor the content changes, call the OnChange method
This.getcontext (). Getcontentresolver (). Notifychange (URI, new Contentobserver (New Handler ()) {
public void OnChange (Boolean selfchange) {
Business processing can be done here
}
});

Two Actual combat

Said so much, it is time to understand the use of contentprovider, we use the SQLite storage data. Of course, is it better for us to use the contact data directly?


1: First we define dbhelper inherit Sqliteopenhelper, and build the table.

The code is as follows Copy Code

Package Com.dongzi;

Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
Import Android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends Sqliteopenhelper {

Static final String db_name = "dongzi.db";
static final int db_version = 1;
Static final String table= "Persion";
Static final String table_column_name= "NAME";
Static final String table_column_phone= "PHONE";
Static final String create_table = "CREATE TABLE persion" (ID integer primary key autoincrement,name varchar () phone Varch AR (40)) ";
Static final String drpo_table= "drop TABLE if exists persion";
Public DBHelper {
Super (context, db_name, NULL, db_version);

}

@Override
public void OnCreate (Sqlitedatabase db) {
Db.execsql (create_table);
}

@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
This is actually a comparison version, and then upgrade the database, for example, add a field, or delete a field, or add a table
Db.execsql (drpo_table);
OnCreate (DB);
}

}

2: Then define Mycontentprovider to inherit ContentProvider and initialize Urimatcher match at class load time, as well as authorization authority, This contentprovider needs to be registered in Androidmanifest.xml and added authorization.

The code is as follows:

The code is as follows Copy Code

Package Com.dongzi;

Import Android.content.ContentProvider;
Import Android.content.ContentUris;
Import android.content.ContentValues;
Import Android.content.UriMatcher;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.net.Uri;
Import Android.text.TextUtils;

public class Mycontentprovider extends ContentProvider {





DBHelper Dbhelper=null;


MIME type


Static final String persions_type= "Vnd.android.cursor.dir/person";


Static final String persion_item_type= "Vnd.android.cursor.item/person";


Return code


static final int codes=2;


static final int code=1;


Authorized


Static final String authority= "Com.dongzi"; Authorized


Static final Urimatcher Urimatcher; URI Matching


static {//Registration matching URI and return code


Urimatcher=new Urimatcher (Urimatcher.no_match); Do not match any path return-1


Urimatcher.adduri (Authority, "Persion", codes); Match Content://com.dongzi/persion return 2


Urimatcher.adduri (Authority, "persion/#", CODE); Match content://com.dongzi/persion/1234 return 1


}





private void init () {


To add an ID to a URI


Uri uri=uri.parse ("content://" +authority+ "/persion");


Contenturis.withappendedid (URI, 1234);


The URI after the build is: content://com.dongzi/person/1234





Gets the ID after the URI


Long Id=contenturis.parseid (Uri.parse ("content://com.dongzi/person/1234"));


Got the ID: 1234


}








@Override


public int Delete (URI Uri, String selection, string[] Selectionargs) {


This method is used for external applications to delete data from ContentProvider.


Sqlitedatabase db=dbhelper.getwritabledatabase ();


int count=0;


Switch (Urimatcher.match (URI)) {


Case codes:


Count = Db.delete (Dbhelper.db_name, Selection, Selectionargs);


Break


Case CODE:


The following method is used to parse out the ID from the URI, and to content://com.dongzi/persion/1234 such a path


To parse, the return value is 10


Long id = Contenturis.parseid (URI);


String where = "id=" + id;//Delete the record for the specified ID


where = =! Textutils.isempty (selection)? "and (" + Selection + ")": "";//attach other conditions to


Count = Db.delete (Dbhelper.db_name, where, Selectionargs);


Break


Default:throw New IllegalArgumentException ("Throw Uri:" +uri.tostring ());





}


Db.close ();


return count;


}


@Override


Public String GetType (Uri uri) {


This method is used to return the MIME type of the data represented by the current URL.


Switch (Urimatcher.match (URI)) {


Case codes:


return persions_type; Here codes represents the collection, so it returns a mime of the collection type


Case CODE:


return persion_item_type;


Default:throw New IllegalArgumentException ("Throw Uri:" +uri.tostring ());


}


}


@Override


Public URI insert (URI uri, contentvalues values) {


This method is used for external applications to add data to ContentProvider.


Sqlitedatabase db= dbhelper.getwritabledatabase ();


Long id=0;


Matching URI


Switch (Urimatcher.match (URI)) {


Return code


Case codes:


Id=db.insert (dbhelper.table, Dbhelper.table_column_name, values);/returns the row number of the record, the primary key is int, and is actually the primary key value


Return Contenturis.withappendedid (URI, id);


Case CODE:


Id=db.insert (dbhelper.table, Dbhelper.table_column_name, values);/returns the row number of the record, the primary key is int, and is actually the primary key value


String path = uri.tostring ();


Return Uri.parse (path.substring (0, Path.lastindexof ("/")) +id); Replace ID


Default:throw New IllegalArgumentException ("Throw Uri:" +uri.tostring ());


}


}


@Override


public Boolean onCreate () {


is created the first time another application accesses it.


DBHelper =new DBHelper (GetContext ());


return false;


}


@Override


Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {


This method is used for external applications to obtain data from ContentProvider.


Sqlitedatabase db=dbhelper.getwritabledatabase ();


Cursor Cursor=null;


Switch (Urimatcher.match (URI)) {


Case codes:


Cursor=db.query (Dbhelper.db_name, projection, selection, Selectionargs, NULL, NULL, sortOrder);


Break


Case CODE:


The following method is used to parse out the ID from the URI, and to content://com.dongzi/persion/1234 such a path


To parse, the return value is 10


Long id = Contenturis.parseid (URI);


String where = "id=" + id;//gets the record of the specified ID


where = =! Textutils.isempty (selection)? "and (" + Selection + ")": "";//attach other conditions to


Cursor=db.query (dbhelper.db_name, projection, where, Selectionargs, NULL, NULL, sortOrder);


Break


Default:break;


}


return cursor;


}


@Override


public int update (URI uri, contentvalues values, String selection, string[] Selectionargs) {


This method is used for external applications to update data in ContentProvider.


return 0;


}

}

If we basically understand the basic knowledge of the above, then these code is not ugly to understand, in fact, is very simple, not directly operate DBHelper class, but through ContentProvider indirect operation, and Operation ContentProvider is too through
Contentresolver This class, the data can be accessed by implementing different applications.

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.