Android Learning--the content of sharing data across programs provides its exploration

Source: Internet
Author: User

What is a content provider?

What is the function of a content provider that shares data across programs? When we see this name, it's the word "cross-procedure" that gives us the most information. The key is the word, the function of the content provider is mainly used to achieve data sharing between different reference programs, it provides a complete mechanism to allow one program to access data in another program, It also guarantees the security of the data being accessed, and the current use of the content provider is a standard way for Android to share data across programs. Unlike the two global readability modes in file storage and sharepreferences storage, content providers can choose to share only that part of the data, thus ensuring that the privacy data in our programs is not a risk of leaking.

But before we understand the content provider, we need to understand the runtime permissions of Android, which doesn't require us to explain what runtime permissions are, because we've actually used them before, such as "Camera Permissions", "Photo Permissions", "Location permissions" and so on!

Run-time permissions

Android will have all the permissions broadly divided into two categories, one is ordinary permissions, the other is dangerous permissions, we have the dangerous permissions in the following collation out, for later we refer to use:

Give me a little chestnut.

The following is for the phone we write a small demo, in fact, logic is very simple, said the direct point is a word "have the right to call directly, no permission on the request is over and then hit." Here's what we do with click events

        Use the Checkselfpermission function to check that there are no runtime permissions/        /permissions to invoke the call () method directly below, without requesting permission        //Checkselfpermission ( Mainactivity.this, Android. Manifest.permission.CALL_PHONE) is equal to packagemanager.permission_granted        //permission_granted Consent permission        if ( Contextcompat.checkselfpermission (Mainactivity.this, Android. Manifest.permission.CALL_PHONE)! = packagemanager.permission_granted) {                        // Activitycompat requestpermissions Request Permission            //The second parameter is a string array, we need to put the permission name of the request into the array can            //The third parameter is the request code, This request code we in the following permissions callback can be used to make a judgment, judge is that permission to do the corresponding operation            activitycompat.requestpermissions (Mainactivity.this,new string[]{ Android. manifest.permission.call_phone},1);        } else {call            ();        }

And then the call () method that we called and the callback method after the last permission request came back:

    To prevent an exception from occurring, write here public    Void Call () {         try {             Intent Intent = new Intent (intent.action_call);             Intent.setdata (Uri.parse ("tel:10086"));             StartActivity (intent);         } catch (SecurityException e) {             e.printstacktrace ();         }    }    All of the permissions callbacks are here, and we determine which permissions are based on Requestcode    @Override public    void Onrequestpermissionsresult (int requestcode , string[] permissions, int[] grantresults) {        Super.onrequestpermissionsresult (requestcode, permissions, Grantresults);        Switch (requestcode) {case            1:                if (grantresults.length>0 && grantresults[0] = = packagemanager.permission_granted) {call                    ();                } else {                    Toast.maketext (this, "call requires permission to use", Toast.length_long). Show ();}}    

Accessing data in other programs requires-contentresolver

For each application, if you want to access the data shared by the content provider, you have to use the Contentresolver class to get an instance of the class through the Getcontentresolver () method in the context class. The Contentresolver class also provides a series of methods to perform CRUD operations on data, insert () add update () updates delete () to remove query () queries

A crud that differs from Sqlitedatabase,contentresolver does not receive table name parameters, but instead uses a URI parameter representation. This parameter is called the content URI, and the content URI establishes a unique identifier for the data table in the content provider, which is mainly composed of two parts, part of the authority, which is used to differentiate the different applications, generally to avoid conflicts, will take the form of a package to name, The other part is that Path,path is distinguished from the table in the same application, and is usually added behind the authority. Of course only these two parts are not enough, we need to precede the agreement statement, so the standard form we give an example:

Content://com.example.app.provider/table1 content://is our Head agreement Com.example.app.provider is Authority/table1 is path

After we get a URI string, we also need to parse it into a URI object to use, and the parsing method is simple as follows:

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

With this URI object, we can use it to query the data, the code is as follows:

cursor cursor = getcontentresolver (). Query (

URI that specifies that one of the following tables is queried for an application

Projection, specifying the column name of the query

Selection, specifying the WHERE constraint

Selectionargs, providing a specific value for the placeholder in the where

SortOrder); Specify how query results are sorted

When the query is complete, it is still a cursor object, and we can read the data from the cursor object one at a time.

The idea of reading is still to traverse all the lines of the cursor by moving the cursor's position, and then take out every row. China's data is no longer code as follows:

if (cursor! = NULL) {

while (Cursor.movenext ()) {

String column1 = cursor.getstring (Cursor.getcolumnindex ("Column1"));

Int column1 = Cursor.getint (Cursor.getcolumnindex ("Column1"));

}

}

Master the more complex query, the rest of the increase, deletion, modification is relatively simple, we will not say!

Let's read the contacts.

Here we write a small demo, to read the contact information, and then show it in a ListView, the specific code is as follows:

public class Contactsactivity extends Appcompatactivity {///adapter and an array to store contact information arrayadapter<string> adapter;    list<string> list = new arraylist<> ();        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_contacts);        ListView contactslist = (ListView) Findviewbyid (R.id.contactslistview); adapter = new Arrayadapter<string> (Contactsactivity.this, Android.        R.layout.simple_list_item_1, list);        Contactslist.setadapter (adapter); First check that there is no permission to get the address book, if not first request permission if (Contextcompat.checkselfpermission (this, Android. Manifest.permission.READ_CONTACTS)! = packagemanager.permission_granted) {activitycompat.requestpermissions (thi S,new string[]{android.        manifest.permission.read_contacts},2);        }else {readcontacts ();        }}//Get contact private void readcontacts () {cursor cursor = NULL;        try{      cursor = Getcontentresolver (). query (Contactscontract.commondatakinds.phone.content_uri,null,null,null,null);                      if (cursor! = NULL) {while (Cursor.movetonext ()) {//Contact name String displayName = cursor.getstring (Cursor.getcolumnindex (ContactsContract.CommonDataKinds.Phone.DI                      Splay_name)); Contact's cell phone number = cursor.getstring (Cursor.getcolumnindex (ContactsContract.CommonDataKinds.Ph One.                      number));                  List.add (displayname+ "\ n" +number);              }//Send a message to the adapter that the data has changed, this time it will re-refresh the data adapter.notifydatasetchanged ();        }}catch (Exception e) {e.printstacktrace ();            }finally {if (cursor! = NULL) {cursor.close ();  }}}//get permission results @Override public void Onrequestpermissionsresult (int requestcode, string[] permissions, InchT[] grantresults) {Super.onrequestpermissionsresult (Requestcode, permissions, grantresults); Switch (requestcode) {case 2:if (grantresults.length>0&& grantresults[0] = = Packagem Anager.                permission_granted) {readcontacts ();                }else {Toast.maketext (this, "access to Address Book requires permission", Toast.length_short). Show (); }        }    }}

Create your own content provider

As I said earlier, if you want to implement the ability to share data across programs, the official recommendation is to use a content provider, and we can create a new class to inherit ContentProvider's way of creating a content provider of our own. 6 abstract methods in ContentProvider we all rewrite

OnCreate ()

When the content provider is initialized, it is usually done in the database creation and upgrade operation, return TRUE indicates success, return False indicates failure, note that the content provider will be initialized only when Contentresolver attempts to access our database.

Query ()

Query the data from the content provider, use the URI parameter to determine which table to query, the specific parameters we are not talking about, as we have said before, the specific results of the query is stored in the cursor object returned

Insert ()

Add data we don't have to say it again. A URI to represent this record is returned after success.

Update ()

Note that the affected function is returned as a return value

Delete ()

This, as well as the update, returns the number of rows affected as return values

GetType ()

Returns the corresponding MIME type based on the content URI passed in

Method specific content We will not say more, you can put yourself into the class inside to see. One thing to note is the URI, one thing we need to note:

* denotes any character that matches any length

# indicates matching numbers of any length

So, we can write a content URI that matches any table:content://com.example.app.provider/*

We can write a content URI that matches any row of data in a table:content://com.example.app.provider/table1/#

Finally, there is a problem, is the content URI matching problem, there is a class Urimatcher class can understand, we do not say more, think you match the URI, when the outside user to CRUD operations when the specific return content is our own custom! The above is what we want to say about content controller content!

Android Learning--the content of sharing data across programs provides its exploration

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.