The use of Android check trap--contentprovider

Source: Internet
Author: User

ContentProvider (content Provider) is a shared component that provides an interface between the system and the application.

Contentprovide requires three key points to work properly:

    • ContentProvider: External provider of data access.
    • Uri:contentprovider's unique identity, the outside world can access the corresponding ContentProvider according to it.
    • Contentresolver

For example, when application a wants to expose its own data so that other applications can operate, you can create a contentprovider within application A to implement related methods and add URIs. Then in other apps (App B) You can access the ContentProvider in app A with Contentresolver and URIs.

Many people will find contentprovider difficult to understand, because many books on the introduction of ContentProvider is after the very complex way to explain, but also the combination of what database, XML and so on, make it look very complex, so many beginners deterred, Actually we don't have to be afraid at all. You can think of ContentProvider as a website, in life you want to visit a website must have a URL address, and here the URI is like this URL address, and then you can use the Contentresolver this URI address to access.

First, to create their own contentprovider
    • Create a ContentProvider.

The

Create your own contentprovider is also very simple, similar to the other components in the four components, first inherit the system ContentProvider to create a class, and implement related methods:

public class Userinfoprovider extends ContentProvider {static final String TAG = UserInfoProvider.class.getSimpleN    Ame ();        @Override public boolean onCreate () {log.i (TAG, "onCreate:");    return false; @Nullable @Override Public Cursor query (@NonNull URI Uri, @Nullable string[] strings, @Nullable String s, @Null        Able string[] STRINGS1, @Nullable String s1) {log.i (TAG, "query:");    return null;        } @Nullable @Override public String getType (@NonNull uri uri) {log.i (TAG, "GetType:");    return null; @Nullable @Override public uri insert (@NonNull uri Uri, @Nullable contentvalues contentvalues) {log.i (T        AG, "insert:");    return null; } @Override public int delete (@NonNull uri Uri, @Nullable String S, @Nullable string[] strings) {LOG.I (TAG,        "Delete:");    return 0; @Override public int update (@NonNull uri Uri, @Nullable contentvalues contentvalues, @NullableString s, @Nullable string[] strings) {LOG.I (TAG, "Update:");    return 0; }}

Then register in Androidmainfest.xml and add authorities, this authorities is passed into the URI, note to set the exported to true so that the outside world can access.

<provider    android:name=".contentprovides.UserInfoProvider"    android:authorities="cn.codingblock.androidadvancestudy.contentprovides.UserInfoProvider"    android:exported="true" />

A basic contentprovider is created, and the next thing to do is to use Contentresolver to access it.

    • Parsing URIs

The parsing URI is parsed using Uri.parse (), passing in the corresponding parameter, with the parameter format:
content://authorities/corresponds to the above Userinfoprovider, a URI is:

Uri uri = Uri.parse("content://cn.codingblock.androidadvancestudy.contentprovides.UserInfoProvider/");
    • Gets the Contentresolver object through Context.getcontentresolver ().

      ContentResolver contentResolver = getContentResolver();

      We will create another project, called TestApp Bar, in this new project to add an activity, in the activity using Contentresolver, through the URI to access the above (in different applications) ContentProvider.

public class Userinforesolveractivity extends Appcompatactivity implements View.onclicklistener {private final static    String TAG = UserInfoResolverActivity.class.getSimpleName ();    Private Contentresolver Contentresolver;    Private URI uri = Uri.parse ("content://cn.codingblock.androidadvancestudy.contentprovides.userinfoprovider/");    Button Btn_insert;    Button Btn_query;    Button btn_update;    Button Btn_delete;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_user_info_resolver);        Gets the Contentresolver object contentresolver = Getcontentresolver ();        Btn_insert = (Button) Findviewbyid (R.id.btn_insert);        Btn_query = (Button) Findviewbyid (r.id.btn_query);        Btn_update = (Button) Findviewbyid (r.id.btn_update);        Btn_delete = (Button) Findviewbyid (r.id.btn_delete);        Btn_insert.setonclicklistener (this); Btn_query.setonclicklistener (This);        Btn_update.setonclicklistener (this);    Btn_delete.setonclicklistener (this);                } @Override public void OnClick (view view) {switch (View.getid ()) {r.id.btn_insert:                Insert ();            Break                Case R.id.btn_query:query ();            Break                Case R.id.btn_update:update ();            Break                Case R.id.btn_delete:delete ();        Break        }} public void Insert () {URI Tempuri = Contentresolver.insert (URI, values);    LOG.I (TAG, "Insert:tempuri =" + Tempuri);        public void query () {cursor cursor = contentresolver.query (URI, NULL, "where", null, NULL);    LOG.I (TAG, "query:cursor =" + cursor);        public void Update () {int n = contentresolver.update (URI, values, "where", null);    LOG.I (TAG, "update:n =" + N); } public void Delete () {int n = contentresolver.deLete (URI, "where", null);    LOG.I (TAG, "delete:n =" + N); }}

It is important to note that this userinfoprovider and userinforesolveractivity are not in the same application, Userinfoprovider in the Androidadvancestudy application, The name of his process is: Cn.codingblock.androidadvancestudy. Userinforesolveractivity in the TestApp application, the process name is: Cn.codingblock.testapp.

In TestApp click on the above increase, check, change, delete button, log as follows:

See, we are doing in the TestApp application of related operations, sure enough to call Androidadvancestudy inside the Userinfoprovider.

Contenprovider is so simple, of course contentprovider function far more than that, we can also combine the database or sharepreference to achieve more complex external data operations.

Second, call the system ContentProvider

In addition to our own creation of the contentprovider,android system also provides us with a rich contentprovider interface, here is the operating system of the contact person as an example to explain how to use the system provides ContentProvider interface.

    • ContactsContract.Contacts.CONTENT_URI: Contact URI.
    • ContactsContract.CommonDataKinds.Phone.CONTENT_URI: Contact phone number URI.

1. Inquiry System Contact

Get the system contact and mobile number through the URI of the system contact person:

public void query () {showcontact = ""; Gets the cursor collection of the contact cursor cursor = getcontentresolver (). query (ContactsContract.Contacts.CONTENT_URI, NULL, NULL, NULL, n    ULL); while (Cursor.movetonext ()) {//Get contact ID String id = cursor.getstring (cursor.getcolumnindex (contactscontract .        contacts._id));        Get Contact name String name = cursor.getstring (Cursor.getcolumnindex (ContactsContract.Contacts.DISPLAY_NAME));                 Get all phone numbers under the current contact ID Cursor phones = getcontentresolver (). Query (ContactsContract.CommonDataKinds.Phone.CONTENT_URI,        NULL, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ID, NULL, NULL); Showcontact + = "--id=" + ID + "|        Name= "+ name +"--\n "; LOG.I (TAG, "onCreate:------id=" + ID + "|        Name= "+ name +"------"); while (Phones.movetonext ()) {String phone = phones.getstring (Phones.getcolumnindex (contactscontract.commondata            Kinds.Phone.NUMBER)); Showcontact + = "Phone =" + Phone + "\ n";        LOG.I (TAG, "oncreate:phone =" + phone);    } phones.close ();    } cursor.close (); Tv_show.settext (showcontact);}

After query log as follows:

12-13 17:19:49.490 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate:------id=1 | Name= Zhang Fei------12-13 17:19:49.490 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 151 1511 151112-13 17:19:49.499 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=2 | Name= Guan yu------12-13 17:19:49.499 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 153 6969 386912-13 17:19:49.499 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: Oncreate:phone = 135 6497 866412-13 17:19:49.499 14978-14978/cn.codingblock.androidadvancestudy I/ ContactProviderActivity:onCreate:phone = 155 5555 555512-13 17:19:49.499 14978-14978/ Cn.codingblock.androidadvancestudy I/contactprovideractivity:oncreate:phone = 133 3333 333312-13 17:19:49.508 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate:------id=3 | Name= LiuPrepared------12-13 17:19:49.508 14978-14978/cn.codingblock.androidadvancestudy I/contactprovideractivity:oncreate:phone = 156 9637 564812-13 17:19:49.508 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate: Phone = 153 7564 864312-13 17:19:49.520 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=14 | Name= bu------12-13 17:19:49.520 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 1567890908712-13 17:19:49.529 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=20 | Name= Sun Quan------12-13 17:19:49.529 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 1536666999912-13 17:19:49.538 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=21 | Name= Cao------12-13 17:19:49.538 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone =1569978896612-13 17:19:49.547 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate:- -----id=22 | Name= Ma Chao------12-13 17:19:49.547 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 15366999966

2. Add System contacts:

public void Insert () {String name = Et_name.gettext (). toString ();    String phone = Et_phone.gettext (). toString (); if (textutils.isempty (name) | |        Textutils.isempty (phone)) {Toast.maketext (Getapplicationcontext (), "cannot be empty", Toast.length_long). Show ();    Return    } contentvalues values = new Contentvalues ();    Insert a null value to get the id Uri Rawcontacturi = getcontentresolver (). Insert (ContactsContract.RawContacts.CONTENT_URI, values);    Long Rawcontactid = Contenturis.parseid (Rawcontacturi);    ------Insert Contact Name------//Set ID values.put (ContactsContract.Data.RAW_CONTACT_ID, Rawcontactid); Set Content Type Values.put (ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM    _type);    Set the name Values.put (ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);    Insert name Getcontentresolver (). Insert (ContactsContract.Data.CONTENT_URI, values);    Values.clear (); ------Insert Contact Phone------values.put (contactscontract.data.    raw_contact_id, Rawcontactid);    Values.put (ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);    Values.put (ContactsContract.CommonDataKinds.Phone.NUMBER, Phone);    Values.put (ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);    Getcontentresolver (). Insert (ContactsContract.Data.CONTENT_URI, values);    Toast.maketext (Getapplicationcontext (), "Add Success", Toast.length_long). Show (); Query ();}

Enter the contact name (Zhuge Liang) and the phone number (13696969696) in the input box and click the Add button, log as follows:

12-13 17:23:37.577 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate:------id=1 | Name= Zhang Fei------12-13 17:23:37.577 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 151 1511 151112-13 17:23:37.589 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=2 | Name= Guan yu------12-13 17:23:37.590 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 153 6969 386912-13 17:23:37.590 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: Oncreate:phone = 135 6497 866412-13 17:23:37.590 14978-14978/cn.codingblock.androidadvancestudy I/ ContactProviderActivity:onCreate:phone = 155 5555 555512-13 17:23:37.590 14978-14978/ Cn.codingblock.androidadvancestudy I/contactprovideractivity:oncreate:phone = 133 3333 333312-13 17:23:37.603 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate:------id=3 | Name= LiuPrepared------12-13 17:23:37.603 14978-14978/cn.codingblock.androidadvancestudy I/contactprovideractivity:oncreate:phone = 156 9637 564812-13 17:23:37.603 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate: Phone = 153 7564 864312-13 17:23:37.616 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=14 | Name= bu------12-13 17:23:37.617 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 1567890908712-13 17:23:37.630 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=20 | Name= Sun Quan------12-13 17:23:37.630 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 1536666999912-13 17:23:37.657 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=21 | Name= Cao------12-13 17:23:37.657 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone =1569978896612-13 17:23:37.671 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate:- -----id=22 | Name= Ma Chao------12-13 17:23:37.671 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity:oncreate : Phone = 1536699996612-13 17:23:37.712 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: OnCreate:------id=23 | Name= Zhuge Liang------12-13 17:23:37.712 14978-14978/cn.codingblock.androidadvancestudy i/contactprovideractivity: Oncreate:phone = 13696969696

As you can see, Zhuge Liang and the telephone number have been successfully added.

Of course, in addition to the above several URIs, the system's ContentProvider interface has a lot of, not one example, use when you can query the official API.

Finally want to say is, this series for Bo master on Android knowledge again comb, check the learning process, on the one hand is forgetting things to review again, on the other hand believe in the process of re-learning will have a huge new harvest, if you also have with me the same idea, may wish to pay attention to my study together , explore each other and make progress together!

Reference documents:

    • Explore the art of Android development
    • "Android Development advanced from small to expert"

The use of Android check trap--contentprovider

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.