Android-android the content provider to access data from other programs

Source: Internet
Author: User

There are two common uses of content providers, one is to use existing content to read and manipulate data in the corresponding program, and to create your own content provider to provide external access to the data of our programs. First of all, let's learn the first kind.

If an application provides external access to its own data through a content provider, other applications can access that part of the data. Android phone books, text messages, media libraries and other programs all provide similar external interfaces, which makes it possible for third-party applications to make full use of this part of the data for better functionality.

Basic usage of 1.ContentResolver

For each application, if you want to access the data that is shared in the content provider, you must use the Contextresolver class, which can be accessed through the Getcontentresolver () in the context class. method to get the object of the Contentresolver class. Some operations similar to databases are available in the Contentresolver class.

The method of adding and deleting from sqlitedatabase,contentresolver is not a parameter to receive the table name, but instead uses a URI parameter, which is called the content URI.

The content URI provides a unique identifier for the data in the content provider, which consists of two main parts: authority and path. Authority is used to differentiate between different applications, typically in the form of a conflict, by naming the application's package name. For example, a program's package name is Com.example.demo, then the program corresponding to the authority can be named Com.example.demo.provider. Path is used to differentiate between different tables in the same application and is usually added to the back of the authority. For example, there are two tables in the data for an application: table1, table2, then you can name path/table1 and/table2, then combine authority and path. The content URI becomes Com.example.demo.provider/table1 and Com.example.demo.provider/table2. However, it is difficult to recognize that these two strings are two content URIs, so we also need to add a protocol declaration to the header of the string. Therefore, the most standard format for content URIs is:

Content://com.example.demo.provider/table1

After we get the content URI string, we also need to parse it into a URI object before it can be passed in as a parameter. We can parse this by using the parse method in the URI.

Uri uri = uri.parse ("Content://com.example.demo.provider/table1");

(1). Querying Data

Now we can use this object to query the data in the Table1 table

cursor cursor = getcontentresolver (). Query (final URI Uri, string[] projection, String selection, string[] Selectionargs, String SortOrder, cancellationsignal cancellationsignal)

1.uri, specifies that a table under one program is queried

2.projection, specifying the column name of the query

3.selection, specifying the query condition, equivalent to the condition behind the Where in the SQL statement

4.selectionArgs, give a specific value to the placeholder in selection

5.orderBy, specifying how query results are sorted

6.cancellationSignal, canceling the semaphore that is in operation

(2). Inserting Data

Contentvalues values = new Contentvalues ();

Values.put ();

Getcontentresolver.insert (uri,values);

(3). Update Data

Contentvalues values = new Contentvalues ();

Values.put ();

Getcontentresolver.update (URI, values, "Column1 =?") and Column2 =? ", New string[]{" text "," 1 "});

Note that the selection and Selectionargs parameters are used to constrain the data that you want to update to prevent all rows from affecting.

(4). Delete Data

Getcontentresolver (). Delete (URI, "Column2 =?", New string[]{"1"});

2. Reading contacts

Now we use the previous knowledge to do a small demo, to read the phone phone book contact

1  Public classMainactivityextendsAppcompatactivityImplementsView.onclicklistener {2     PrivateButton Buttoncall =NULL;3     PrivateRecyclerview Myrecyclerview =NULL;4     PrivateMyadapter Myadapter =NULL;5     Privatelist<bean> datas =NULL;6 7 @Override8     protected voidonCreate (@Nullable Bundle savedinstancestate) {9         Super. OnCreate (savedinstancestate);Ten Setcontentview (r.layout.activity_main); One Initview (); A     } -  -     Private voidInitview () { theButtoncall =(Button) Findviewbyid (r.id.id_button_readcontacts); -Buttoncall.setonclicklistener ( This); -Myrecyclerview =(Recyclerview) Findviewbyid (R.id.id_recyclerview); -Datas =NewArraylist<>(); +Myadapter =NewMyadapter ( This, datas); -Myrecyclerview.setlayoutmanager (NewLinearlayoutmanager ( This, Linearlayoutmanager.vertical,false)); + Myrecyclerview.setadapter (myadapter); A     } at  - @Override -      Public voidOnClick (View v) { -         if(Contextcompat.checkselfpermission ( This, Manifest.permission.READ_CONTACTS)! =packagemanager.permission_granted) { -Activitycompat.requestpermissions ( This,NewString[]{manifest.permission.read_contacts}, 1); -         } in         Else -         { to readcontacts (); +         } -     } the  * @Override $      Public voidOnrequestpermissionsresult (intRequestcode, @NonNull string[] permissions, @NonNullint[] grantresults) {Panax Notoginseng         if(Requestcode = = 1) { -             if(Permissions.length > 0 && grantresults[0] = =packagemanager.permission_granted) { the readcontacts (); +}Else { AToast.maketext ( This, "Permissions not allowed!", Toast.length_short). Show (); the             } +         } -     } $  $     Private voidreadcontacts () { -cursor cursor =NULL; -         Try { thecursor = Getcontentresolver (). Query (ContactsContract.CommonDataKinds.Phone.CONTENT_URI,NULL,NULL,NULL,NULL); -             if(Cursor! =NULL)Wuyi             { the                  while(Cursor.movetonext ()) -                 { WuString name =cursor.getstring (Cursor.getcolumnindex (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); -String PhoneNumber =cursor.getstring (Cursor.getcolumnindex (ContactsContract.CommonDataKinds.Phone.NUMBER)); AboutBean Bean =NewBean (name, phonenumber); $ Datas.add (bean); -                 } -             } -LOG.I ("main", "size =" +datas.size ()); A myadapter.notifydatasetchanged (); +         } the         Catch(Exception e) -         { $ e.printstacktrace (); the}finally{ the             if(Cursor! =NULL) the             { the cursor.close (); -             } in         } the     } the}

Layout file Code:

1 <?XML version= "1.0" encoding= "Utf-8"?>2 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"3 Android:layout_width= "Match_parent"4 Android:layout_height= "Match_parent"5 android:gravity= "Center"6 android:orientation= "vertical">7     <Android.support.v7.widget.RecyclerView8         Android:id= "@+id/id_recyclerview"9 Android:layout_weight= "Ten"Ten Android:layout_width= "Match_parent" One Android:layout_height= "0DP"></Android.support.v7.widget.RecyclerView> A     <Button -         Android:layout_weight= "1" - Android:id= "@+id/id_button_readcontacts" the Android:text= "read" - android:textsize= "20SP" - Android:layout_width= "Wrap_content" - Android:layout_height= "0DP" /> + </LinearLayout>

Effect Show:

Android-android the content provider to access data from other programs

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.