Learn to call system Contentprivider to get and add contacts as an example

Source: Internet
Author: User

To get and add contacts as an example, learn to call system-provided ContentProvider

Android is already providing a contact contentprovider when it comes to making contact with the app.
Consists of 3 tables
1.raw_contacts table
CONTACT_ID the ID of the person who stored the contact
The table holds all the created phone contacts, one row for each contact, and a column in the list that identifies whether the contact was deleted, the table holds two Id:rawcontactid and ContactID, and the Contacts table and Raw_contacts table are linked together. This table holds the contact's Rawcontactid, ContactID, number of contacts, time of the last contact, whether it was added to the collection, the name displayed, and the Hanyu Pinyin used for sorting.
2.data table
This table is used to store all the contact details.
There may be multiple data for a contact, where the more important fields are the data type, the contact ID, and the data content,
One of the fields Mime_type is the data type (phone, email, name)

3.mimeType table
is the contact. All database Type options

The code section, layout is not listed.

 PackageCom.user.android2_lesson_06_systemcontentprivider;ImportAndroid.content.ContentResolver;ImportAndroid.content.ContentValues;ImportAndroid.database.Cursor;ImportAndroid.net.Uri;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.Toast;/** * Call system-provided Contentprivider * today to get contacts for example * system when writing a contact this app, has provided a contact person's Contentprivider * Look at the system provides the contact database * source code inside. Let's take a look at * raw_contacts table * CONTACT_ID store Contact ID * * Data table This represents the details used to store all contacts. * A contact information may be divided into multiple data, * where the more important field is the data type, contact ID, and data content * There is a field mime_type is the type of data (phone, mailbox, name, etc.) * mime_type table * Contact all data type options * * See source code can To see that Contentprivider has two URIs, two are available * but after 4.0 only the URI after the semicolon is used, which is compatible with the lower version * * What do you do if you want to get contact data? * 1. Get all Contact ID * 2. All data messages for this contact are queried according to ID * */ Public  class mainactivity extends appcompatactivity {    PrivateButton mgetcontacts;PrivateButton mupdatacontacts;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Mgetcontacts = (Button) Findviewbyid (r.id.getcontacts);        Mupdatacontacts = (Button) Findviewbyid (r.id.updatacontacts); Mgetcontacts.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View view) {//access to contact person hereContentresolver CR = Getcontentresolver ();//1. Get all Contact IDsCursor Cursorid = Cr.query (Uri.parse ("Content://com.android.contacts/raw_contacts"),Newstring[]{"contact_id"},NULL,NULL,NULL);if(Cursorid.getcount () = =0) {Toast.maketext (mainactivity. This,"no contact.", Toast.length_short). Show ();return; }//2. Get all the information for each contact according to the ID                 while(Cursorid.movetonext ()) {//Get the ID of the stringString ContactID = cursorid.getstring (Cursorid.getcolumnindex ("contact_id"));//ID to the data database to find all the contact informationCursor contactdata = Cr.query (Uri.parse ("Content://com.android.contacts/data"),Newstring[]{"Data1","MimeType"},"raw_contact_id =?",NewString[]{contactid},NULL);//Traverse get contact information                     while(Contactdata.movetonext ()) {String data1 = contactdata.getstring (Contactdata.getcolumnindex ("Data1"));//Type of data receivedString MimeType = contactdata.getstring (Contactdata.getcolumnindex ("MimeType"));if("Vnd.android.cursor.item/email_v2". Equals (MimeType)) {LOG.I ("Mailbox", data1); }Else if("Vnd.android.cursor.item/phone_v2". Equals (MimeType)) {LOG.I ("Mobile:", data1); }Else if("Vnd.android.cursor.item/name". Equals (MimeType)) {LOG.I ("Name", data1); }                    }//Close cursor object to free memoryContactdata.close (); }//Close cursor object to free memoryCursorid.close ();//3. Add permissions to allow read Contentprivider}        });//Through the above analysis, we want to insert a contact, we need the following actions://1, first go to the Raw_contacts table to add the ID;///2, then use the ID to go to the data table to add a variety of information. Mupdatacontacts.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View view) {Contentresolver Cr2 = Getcontentresolver ();//Query the Raw_contacts table first, get the latest contact's primary key, and then the primary key +1, which is the ID of the contact you want to insertCursor Cursorid = Cr2.query (Uri.parse ("Content://com.android.contacts/raw_contacts"),Newstring[]{"_id"},NULL,NULL,NULL);//The default contact ID is 1.                intcontact_id =1;if(Cursorid.movetolast ()) {//Get the primary key                    int_id = Cursorid.getint (Cursorid.getcolumnindex ("_id"));//Primary key +1, which is the contact you want to insertcontact_id = ++_id; }//Add contact_id to the Raw_contacts tableContentvalues values =NewContentvalues (); Values.put ("contact_id", contact_id); Cr2.insert (Uri.parse ("Content://com.android.contacts/raw_contacts"), values);//Empty contentvalues insert nameValues.clear (); Values.put ("Data1","Fujiwara Tuo Hai"); Values.put ("MimeType","Vnd.android.cursor.item/name"); Values.put ("raw_contact_id", contact_id); Cr2.insert (Uri.parse ("Content://com.android.contacts/data"), values);//Empty contentvalues Insert PhoneValues.clear (); Values.put ("Data1","110119120"); Values.put ("MimeType","Vnd.android.cursor.item/phone_v2"); Values.put ("raw_contact_id", contact_id); Cr2.insert (Uri.parse ("Content://com.android.contacts/data"), values);                Cursorid.close (); Toast.maketext (Getapplicationcontext (),"Insert data Success", Toast.length_short). Show ();    }        }); }}
这里注意需要添加读写权限  <uses-permission android:name="android.permission.READ_CONTACTS"/>    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>

Learn to call system Contentprivider to get and add contacts as an example

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.