Android Novice Learning Note----ContentProvider (ii) contentobserver simple use

Source: Internet
Author: User

Now there is an application that provides its own data to other applications through ContentProvider, and application B acquires the data provided in app A through contentresolver and displays it in the ListView, Instead, apply C to modify the data in app a by contentresolver, or add new data. The question now is, after applying C to modify the data in a, what is displayed in the ListView of App B is the historical data ...

The specific procedures are as follows:

ContentProvider and insert data are reused for the two apps in the previous article, and then create a new app to get the data from the ContentProvider and show it in a ListView:

Layout file add a ListView in activity _main.xml:

1 < ListView 2 3         Android:id = "@+id/lv" 4 5         android:layout_width= "Match_parent"67        android: Layout_height= "Wrap_content"></ListView>

The layout file Item_layout.xml is used to display entries in the ListView:

1 <?XML version= "1.0" encoding= "Utf-8"?>2 3 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"4 5 Android:layout_width= "Match_parent"6 7 Android:layout_height= "Match_parent"8 9 android:orientation= "Horizontal" >Ten  One     <TextView A  -         Android:id= "@+id/tv_id" -  the Android:layout_width= "Wrap_content" -  - Android:layout_height= "Wrap_content" -  + Android:layout_weight= "1"/> -  +     <TextView A  at         Android:id= "@+id/tv_name" -  - Android:layout_width= "Wrap_content" -  - Android:layout_height= "Wrap_content" -  in Android:layout_weight= "1"/> -  to     <TextView +  -         Android:id= "@+id/tv_gender" the  * Android:layout_width= "Wrap_content" $ Panax Notoginseng Android:layout_height= "Wrap_content" -  the Android:layout_weight= "1"/> +  A     <TextView the  +         Android:id= "@+id/tv_age" -  $ Android:layout_width= "Wrap_content" $  - Android:layout_height= "Wrap_content" -  the Android:layout_weight= "1"/> - </LinearLayout>

Mainactivity Add the code that gets the data and displays it to the ListView:

1 protected voidonCreate (Bundle savedinstancestate) {2 3         Super. OnCreate (savedinstancestate);4 5 Setcontentview (r.layout.activity_main);6 7URI = Uri.parse ("Content://cn.csc.content_provider/t_student");8 9cursor cursor = getcontentresolver (). Query (URI,Newstring[]{"id as _id", "name", "Gender", "Age"},NULL,NULL,NULL);Ten  OneLV =(ListView) Findviewbyid (r.id.lv); A  -Lv.setadapter (NewSimplecursoradapter ( This, R.layout.item_layout,cursor, -  the                    Newstring[]{"_id", "name", "Gender", "Age"},New int[]{r.id.tv_id,r.id.tv_name,r.id.tv_gender,r.id.tv_age}]); -  -}

Operation Result:

The above is used to simplecursoradapter this adapter class, its construction parameter description:

The first parameter indicates an instance of the application context

The second parameter indicates the layout ID displayed for each entry in the ListView

The third parameter indicates the cursor result set object that holds the data to be displayed

The four and fifth parameters together indicate that each field in the cursor result set is placed in the control in the layout file, and the elements in the two arrays correspond in order one by one. The fourth parameter is the string[] type, each element is the name of the field in the result set, and the fifth parameter is the int[] type, each parameter is the resource ID of each control in the layout file.

One of the special considerations here is that the simplecursoradapter requires that a field named _id be present in the table, otherwise it will get an error, thus stopping the normal operation.

But the table I created previously did not have a _id field, but I did not want to change the definition of the table, but in the query () method, you would use the alias in the second parameter of the field you want to query: As in the above notation:

cursor cursor = getcontentresolver (). Query (URI, new string[]{"id as _id", "name", "Gender", "age"}, NULL, NULL, NULL);

In this way, the field names in the result set are changed from the ID to the _id,simplecursoradapter to be used normally.

However, by using the Insert () method to add data from an app that acts as a C role, the ListView in the current app does not change or displays incomplete historical data!!!

For this problem, Android provides a class called Contentobserver, which is used to see if the data for a particular URI has changed, and when it changes, it can be handled as appropriate.

Use of Contentobserver:

The First step: Register Contentobserver in App B, declare the URI to observe, and rewrite its onchange method to complete the business logic that is required.

The specific code is as follows:

1URI = Uri.parse ("Content://cn.csc.content_provider/t_student");2 3Getcontentresolver (). Registercontentobserver (URI,true,NewContentobserver (NewHandler ()) {4 5 @Override6 7                 Public voidOnChange (BooleanSelfchange) {8 9                      //TODO auto-generated Method StubTen  One                      Super. OnChange (selfchange); A  -LOG.I ("Test", "changed"); -  thecursor cursor = getcontentresolver (). Query (URI,Newstring[]{"id as _id", "name", "Gender", "Age"},NULL,NULL,NULL); -  -LV =(ListView) Findviewbyid (r.id.lv); -  +Lv.setadapter (NewSimplecursoradapter (mainactivity. This, R.layout.item_layout,cursor, -  +                              Newstring[]{"_id", "name", "Gender", "Age"},New int[]{r.id.tv_id,r.id.tv_name,r.id.tv_gender,r.id.tv_age}]); A  atToast.maketext (mainactivity. This, "The data has changed, the ListView display has been refreshed", Toast.length_short). Show (); -  -                } -  -               -  in});

Second step: In Application A in the Insert (), update (), delete () method, notify the Content observer observing these URIs, inform the data change, will trigger its corresponding onchange method, complete the data change business.

The specific code is as follows:

1 getcontext (). Getcontentresolver (). Notifychange (URI, null);

Current ListView Status:

In application C, test adding and deleting methods, observe the operation in application B:

Increase:

1  Public voidTestinsert () {2 3Uri uri = uri.parse ("Content://cn.csc.content_provider/t_student");4 5Contentvalues values =Newcontentvalues ();6 7Values.put ("name", "CSC");8 9Values.put ("Gender", "male");Ten  OneValues.put ("Age", 25); A  -Uri Uri2 =GetContext (). Getcontentresolver (). Insert (URI, values); -  theLOG.I ("Test", uri2.tostring ()); -  -}

Operation Result:

By deleting:

1  Public void Testdelete () {23            Uri uri = uri.parse ("content://cn.csc.content_provider/t_student"); 4 5            int New string[]{"7"}); 6 7            LOG.I ("Test", i+ ""); 8 9 }

Operation Result:

Change:

1  Public voidtestupdate () {2 3Uri uri = uri.parse ("Content://cn.csc.content_provider/t_student");4 5Contentvalues values =Newcontentvalues ();6 7Values.put ("name", "DQRCSC");8 9Values.put ("Gender", "male");Ten  OneValues.put ("Age", 24); A  -            inti = GetContext (). Getcontentresolver (). Update (URI, values, "ID&GT;?",Newstring[]{"3"}); -  theLOG.I ("Test", i+ "" "); -  -}

Operation Result:

Above, is the simple use of contentobserver.

Android Novice Learning Note----ContentProvider (ii) contentobserver simple use

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.