Androsh 14th Day---Share data with contentprovider and listen to shared data using Contentresolver

Source: Internet
Author: User

ContentProvider:

First, when an application inherits the ContentProvider class and overrides the method used to provide data and store data, it can share its data with other applications. Although the use of other methods can also share data, but the way data access will vary depending on how the data is stored, such as: the use of file-based data sharing, the need for file operations to read and write data, the use of sharedpreferences shared data, You need to read and write data using the Sharedpreferences API. The benefit of using ContentProvider to share data is to unify the way data is accessed.

The second step is to use <provider> to configure the ContentProvider in Androidmanifest.xml, in order for other applications to find the ContentProvider, ContentProvider Using authorities (hostname/domain name) to uniquely identify it, you can think of ContentProvider as a website (imagine, the site is also providing data), authorities is his domain name:
<manifest. >
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<provider android:name= ". Personcontentprovider "android:authorities=" Cncsdn.provider.personprovider "/>
</application>
</manifest>
Note: Once the app inherits the ContentProvider class, we'll refer to this app as the ContentProvider (content provider) later. The name of the name here is set to be arbitrarily set, authorities general set their own path address of the class. Change the first letter of the class name to lowercase.

In addition, to test using the test method of the Android emulator, we first add Instrumentationtestrunner to the instrumentation page in the Androidmanifest.xml configuration file, with the package name set to the current project name , and finally add the Useslibrary option to the application page so you can use it.

Second,the introduction of URIs : The URI represents the data to be manipulated, and the URI consists of two parts: 1 "contentprovider, 2" to manipulate what data is in ContentProvider, a URI consisting of the following: content:// Com.example.sqlite2.provider.usercontentprovider/user

If you want to convert a string to a URI, you can use the parse () method in the Uri class, as follows:
Uri uri = uri.parse ("Content://cn.itcast.provider.personprovider/person")
When you create a ContentProvider class in your project, Shou inherits Contenprovider to implement the appropriate method:

The following is an example of an entity class for the ContentProvider class:

Package Com.example.sqlite2.provider;import Com.example.sqlite2.databases.databasehelper;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;public class Usercontentprovider extends ContentProvider {private static final String authorities = "com. Example.sqlite2.provider.usercontentprovider ";p rivate databasehelper databasehelper;private static Urimatcher urimatcher;private static final int userscode = 1;private static final int usercode = 2;private String user_dir = "Vnd.and Roid.cursor.dir/user ";p rivate String user_item =" Vnd.android.cursor.item/user "; static {urimatcher = new Urimatcher ( Urimatcher.no_match);//Com.example.sqlite2.provider.usercontentprovider/user represents user information Operation Urimatcher.adduri ( Authorities, "user", userscode);//COM.EXAMPLE.SQLITE2.PROVIDER.USERCONTENTPROVIDER/USER/1 represents query user information Urimatcher. Adduri (Authorities, "user/#", Usercode);} @Overridepublic Boolean onCreate () {this.databasehelper = new Databasehelper (GetContext (), 1); return false;} @Overridepublic Cursor query (Uri uri, string[] projection, string selection,string[] Selectionargs, string sortOrder) {Cu Rsor c = null; Sqlitedatabase db = Databasehelper.getwritabledatabase (); switch (Urimatcher.match (URI)) {case usercode://operation of several entries long id = Contenturis.parseid (URI); c = db.query ("User", Projection, "Userid=?", new string[] {"" + ID}, NULL, NULL, SortOrder) ; Break;case userscode:c = Db.query ("User", projection, selection, Selectionargs, Null,null, SortOrder); Break;default: throw new IllegalArgumentException ("Unknown uri" + uri);} return c;} @Overridepublic string GetType (Uri uri) {String value = Null;switch (Urimatcher.match (URI)) {Case Userscode:value = User_d Ir;break;case usercode:value = User_item;break;} return value;} Com.example.sqlite2.provider.usercontentprovider/user represents the user information operation @overridepublic URI insert (URI Uri, ConteNtvalues values) {if (Urimatcher.match (URI)! = Userscode) {throw new IllegalArgumentException ("Unknown uri" + uri);} Sqlitedatabase db = Databasehelper.getwritabledatabase (); Long rowId = Db.insert ("User", "username", values);// Register this flag getcontext (). Getcontentresolver (). Notifychange (URI, null); return Contenturis.withappendedid (URI, rowId);} @Overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {int rows =-1; Sqlitedatabase db = Databasehelper.getwritabledatabase (); switch (Urimatcher.match (URI)) {case usercode://operation of several entries long id = Contenturis.parseid (URI); rows = Db.delete ("User", "userid=?", new string[] {"" + ID});d b.close (); Break;case Usersco De:rows = Db.delete ("User", selection, Selectionargs); Break;default:throw new IllegalArgumentException ("Unknown URI" + URI);} return rows;} @Overridepublic int update (URI uri, contentvalues values, String selection,string[] selectionargs) {int rows =-1; Sqlitedatabase db = Databasehelper.getwritabledatabase (); switch (urimatcher.Match (URI)) {case usercode://several entries of the operation long id = Contenturis.parseid (URI); rows = db.update ("User", Values, "Userid=?", New S Tring[] {"" + ID});d b.close (); Break;case userscode:rows = db.update ("User", values, selection, Selectionargs); break;def Ault:throw new IllegalArgumentException ("Unknown uri" + uri);} return rows;}}

Third, Urimatcher class use introduction:
Because the URI represents the data to manipulate, we often need to parse the URI and fetch the data from the URI. The Android system provides two tool classes for manipulating URIs, Urimatcher and Contenturis, respectively. Mastering their use will facilitate our development efforts.
The Urimatcher class is used to match URIs, and it uses the following:
The first step is to take the URI path you need to match all to the registration, as follows:
Constant Urimatcher.no_match indicates a return code that does not match any path
Urimatcher smatcher = new Urimatcher (urimatcher.no_match);
If the match () method matches the Content://cn.csdn.provider.personprovider/person path, a match code of 1 is returned
Smatcher.adduri ("Cn.csdn.provider.personprovider", "person", 1);//Add need to match URI, if match will return match code
If the match () method matches the content://cn.csdn.provider.personprovider/person/230 path, a match code of 2 is returned
Smatcher.adduri ("Cn.csdn.provider.personprovider", "person/#", 2);//#号为通配符
Switch (Smatcher.match (Uri.parse ("CONTENT://CN.CSDN.PROVIDER.PERSONPROVIDER/PERSON/10"))) {
Case 1
Break
Case 2
Break
DEFAULT://does not match
Break
}
After registering a URI that needs to be matched, you can use the Smatcher.match (URI) method to match the input URI, and if the match returns a match, the match code is the third parameter passed in by calling the Adduri () method, assuming that the match content:// Cn.csdn.provider.personprovider/person path, the matching code returned is 1
four, in another project Other2 to refer to the data inside the Sqlite2:

When external applications need to add, delete, modify, and query the data in ContentProvider, you can use the Contentresolver class to get the Contentresolver object, You can use the Getcontentresolver () method provided by the activity. 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 the data in the ContentProvider.
Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder)
This method is used to fetch data from the ContentProvider.

The first parameter of these methods is a Uri, which represents which contentprovider to manipulate and what data to manipulate, assuming that the given is: Uri.parse ("content:// CN.CSDN.PROVIDER.PERSONPROVIDER/PERSON/10 "), Then the contentprovider with the hostname Cn.itcast.provider.personprovider will be manipulated, and the data is the record with ID 10 in the person table.

The

  example is:

Package Com.example.other2;import Android.app.activity;import Android.content.contentresolver;import Android.database.contentobserver;import Android.database.cursor;import Android.net.uri;import Android.os.Bundle; Import Android.os.handler;import Android.os.message;import Android.support.v4.widget.cursoradapter;import Android.support.v4.widget.simplecursoradapter;import Android.view.view;import Android.widget.AbsListView;import Android.widget.abslistview.onscrolllistener;import Android.widget.listview;import Android.widget.TextView;public Class Mainactivity extends Activity implements Onscrolllistener {private static final String URL = "content://com.example. Sqlite2.provider.usercontentprovider/user ";p rivate Boolean flag = false;private Boolean islastrow = False;private Simplecursoradapter adapter;private contentresolver contentresolver;private TextView tv_tip;private ListView lv_users ;p rivate static final int INSERT = 1;private Handler Handler = new Handler () {@Overridepublic void handLemessage (Message msg) {super.handlemessage (msg); switch (msg.what) {case INSERT:tv_tip.setVisibility (view.visible); Flag = True;tv_tip.settext ("Please swipe the menu to load Data"); break;default:break;}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); lv_users = (ListView) Findviewbyid (r.id.lv_users); tv_tip = (TextView) Findviewbyid (r.id.tv_ TIP); tv_tip.setvisibility (view.gone); contentresolver = Getcontentresolver (); Inindate (); Getcontentresolver (). Registercontentobserver (Uri.parse (URL), True,new Usercontentobserver (handler)); Lv_users.setonscrolllistener (this );} private void Inindate () {Cursor c = contentresolver.query (Uri.parse (URL), new string[] {"UserID as _id", "username", "user Pass "," Userphone "}, Null,null," userid desc "); adapter = new Simplecursoradapter (this, r.layout.list_item_users, C,new S Tring[] {"username", "Userpass", "Userphone"},new int[] {r.id.tv_name, r.id.tv_pass, R.id.tv_phone},cursoradapter.fla G_registEr_content_observer); Lv_users.setadapter (adapter);} 

Declare the contentresolver and then use the cursor to create C, call the method in Contentresolver to complete the crud operation
V. Monitoring the change of data in ContentProvider:

You can call Getcontentresolver (). Notifychange (URI, NULL) to notify the visitor registering on this URI when the data changes occur in ContentProvider, as in the following example:

public class Personcontentprovider extends ContentProvider {public URI insert (URI uri, contentvalues values) {Db.insert (" Person "," PersonID ", values); GetContext (). Getcontentresolver (). Notifychange (URI, NULL);}}



If ContentProvider visitors need to be notified of changes to the data, they must use Contentobserver to listen to the data (the data is described by URI), and when the monitor hears the data change notification, The system calls Contentobserver's OnChange () method:

Getcontentresolver (). Registercontentobserver (Uri.parse ("Content://cn.itcast.providers.personprovider/person"),          true, new Personobserver (New Handler ()));p Ublic class Personobserver extends contentobserver{public Personobserver (Handler Handler) {  super (Handler);  } public void OnChange (Boolean selfchange) {     // Business processing can be done here}}



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.