Android Add, delete, change, check contacts in Contacts

Source: Internet
Author: User

I. Permissions

The Operation Address Book must first add 2 permissions in the Androidmanifest.xml.

    <android:name= "Android.permission.READ_CONTACTS"></  Uses-permission>    <android:name= " Android.permission.WRITE_CONTACTS "></uses-permission>

two. Address Book database table introduction (heavy point)

1.minetypes table

2.data table

3.raw_contacts table

Note: 3 Table The second figure is connected to the right of the first figure, because of the size of the reason, cut into 2 pictures.

First of all, contact information before the operation, you must put the database of these 3 tables to look carefully, do not understand it does not matter, and so on the operation of the increase and deletion check, and then back to the control database, so you can more convenient to understand and memory code. Otherwise, the rote code, after two days will forget the all-out.

The contacts are stored in/data/data/com.android.providers.contacts/databases/contacts2.db, and the main tables are:

(1) Raw_contacts: The id,_id property of the contact is the primary key, declared as AutoIncrement, that is, no manual setting is required, other properties do not need to be manually set the default value; display_name attribute is name; Sort_ The key property can be used for sorting after a query

(2) Mimetypes: The type of data stored, such as "Vnd.android.cursor.item/name" for "name" type of data, "VND.ANDROID.CURSOR.ITEM/PHONE_V2" for "phone" type of data ;

(3) Data: storage of specific information; theraw_contact_id property is used to connect the Raw_contacts table, each record represents a specific data;raw_contact_id need to remember, Each contact displayed in the phone corresponds to a fixed raw_contact_id,raw_contact_id corresponds to the _id of the raw_contacts table , and they are the same value, The relationship between the two tables must be cleared. (I just started out without clearing the relationship between the tables, and the meaning of the various fields represented, it was confusing to do, these 3 tables are very important) our main data (email, phone, etc.) are stored in the datasheet;

DATA1 attribute holds total data;

DATA2 Properties:

-If the record holds a name, data2 the name of the store;

-If this record holds the phone, then data2 storage type, such as mobile phone, home appliance;

-If this record holds the organization, then the DATA2 storage type, such as company, other;

-If this record holds the address, then the DATA2 storage type, such as home, unit, etc.

Three. Important Data

Uri

Add, delete, update operations to the Raw_contacts table:

URI = content://com.android.contacts/raw_contacts;

Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

Add, delete, update operation to data table: URI = content://com.android.contacts/data; query data table based on email

URI =content://com.android.contacts/data/emails/filter/*

Query the data table based on the phone number

URI =content://com.android.contacts/data/phone/filter/*

If you want to query the phone by ID, you can URI = Content://com.android.contacts/data;

Then the WHERE condition is: raw_contact_id=? and MimeType =?

MIMETYPE

Tel: vnd.android.cursor.item/phone_v2 name: Vnd.android.cursor.item/name Mail: Vnd.android.cursor.item/email_ V2 Correspondence Address: VND.ANDROID.CURSOR.ITEM/POSTAL-ADDRESS_V2 Organization: vnd.android.cursor.item/ Organization Photo: Vnd.android.cursor.item/photo

Constants in data

data._id: "_id"

Data.display_name: "Display_name"

DATA.DATA1: "Data1"

DATA.DATA2: "Data2"

data.raw_contact_id: "raw_contact_id"

Data.mimetype: "MIMETYPE"

Four. The realization of adding and deleting changes

1.query

(1) Find all the contacts

//read all contacts of contacts//you need to traverse the ID in the Raw_contact table first and get the data from the ID Public voidTestreadall () {//uri = content://com.android.contacts/contactsUri uri = uri.parse ("content://com.android.contacts/contacts");//Accessing the Raw_contacts tableContentresolver resolver = This. GetContext (). Getcontentresolver (); //get _id Propertycursor cursor = resolver.query (URI,NewSTRING[]{DATA._ID},NULL,NULL,NULL);  while(Cursor.movetonext ()) {StringBuilder buf=NewStringBuilder (); //get ID and look up data        intid = cursor.getint (0); Buf.append ("Id=" +ID); URI= Uri.parse ("content://com.android.contacts/contacts/" +id+ "/data"); //Data1 stores the total data for each record, mimetype the type of record, such as phone, email, etc.Cursor Cursor2 = Resolver.query (URI,NewString[]{data.data1,data.mimetype},NULL,NULL,NULL);  while(Cursor2.movetonext ()) {String data= Cursor2.getstring (Cursor2.getcolumnindex ("Data1")); if(Cursor2.getstring (Cursor2.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/name")) {//if it's a nameBuf.append (", name=" +data); }            Else if(Cursor2.getstring (Cursor2.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/phone_v2")) {//if it's a phone,Buf.append (", phone=" +data); }            Else if(Cursor2.getstring (Cursor2.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/email_v2")) {//if it's an email,Buf.append (", email=" +data); }            Else if(Cursor2.getstring (Cursor2.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/postal-address_v2")) {//if it's an addressBuf.append (", address=" +data); }            Else if(Cursor2.getstring (Cursor2.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/organization")) {//if the organizationBuf.append (", organization=" +data); }} String str=buf.tostring (); LOG.I ("Contacts", str); }}

(2) Name search by phone number

//query name by phone number (if the phone is in the Address book when a call comes in, the name is displayed)     Public voidTestreadnamebyphone () {String phone= "12345678"; //uri= Content://com.android.contacts/data/phones/filter/#Uri uri = uri.parse ("content://com.android.contacts/data/phones/filter/" +phone); Contentresolver Resolver= This. GetContext (). Getcontentresolver (); Cursor Cursor= Resolver.query (URI,NewString[]{data.display_name},NULL,NULL,NULL);//returning display_name from the Raw_contact table        if(Cursor.movetofirst ()) {LOG.I ("Contacts", "Name=" +cursor.getstring (0));                                                                                                                             } }

2.Insert

Note: You must insert a data.mimetype (or "MIMETYPE") attribute on a contact when you insert a record such as name, phone, and so on, instead of inserting "mimetype_id"!

For example: Values.put (Data.mimetype, "VND.ANDROID.CURSOR.ITEM/PHONE_V2")

//Add data step by step     Public voidtestaddcontacts () {//Insert the Raw_contacts table and get the _id propertyUri uri = uri.parse ("Content://com.android.contacts/raw_contacts"); Contentresolver Resolver= This. GetContext (). Getcontentresolver (); Contentvalues Values=Newcontentvalues (); Longcontact_id =Contenturis.parseid (Resolver.insert (URI, values)); //Insert Data TableURI = Uri.parse ("Content://com.android.contacts/data"); //Add NameValues.put ("raw_contact_id", contact_id); Values.put (Data.mimetype,"Vnd.android.cursor.item/name"); Values.put ("Data2", "Zdong"); Values.put ("Data1", "Xzdong");        Resolver.insert (URI, values);        Values.clear (); //Add PhoneValues.put ("raw_contact_id", contact_id); Values.put (Data.mimetype,"Vnd.android.cursor.item/phone_v2"); Values.put ("Data2", "2");//Mobile PhoneValues.put ("Data1", "87654321");        Resolver.insert (URI, values);        Values.clear (); //Add EmailValues.put ("raw_contact_id", contact_id); Values.put (Data.mimetype,"Vnd.android.cursor.item/email_v2"); Values.put ("Data2", "2");//UnitValues.put ("Data1", "[email protected]");    Resolver.insert (URI, values); }

Bulk Add data

Core code:

(1) Contentprovideroperation operation = Contentprovideroperation.newinsert (URI). Withvalue ("Key", "value"). Build ();

(2) Resolver.applybatch ("authorities", operations);//Bulk Submission

 Public voidTestaddcontactsintransaction ()throwsException {URI uri= Uri.parse ("Content://com.android.contacts/raw_contacts"); Contentresolver Resolver= This. GetContext (). Getcontentresolver (); ArrayList<ContentProviderOperation> operations =NewArraylist<contentprovideroperation>(); //add a record to the Raw_contact table//here. Withvalue ("account_name", null) must be added, or it will be thrown nullpointerexceptionContentprovideroperation Operation1 =contentprovideroperation. Newinsert (URI). Withvalue ("Account_name",NULL). build ();    Operations.add (Operation1); //to add data to itURI = Uri.parse ("Content://com.android.contacts/data"); //Add NameContentprovideroperation Operation2 =contentprovideroperation. Newinsert (URI). Withvaluebackreference ("Raw_contact_id", 0)            //The second parameter of Withvaluebackreference represents the return ID of the operation referencing Operations[0] as this value. Withvalue ("MimeType", "Vnd.android.cursor.item/name"). Withvalue ("Data2", "Xzdong"). build ();    Operations.add (Operation2); //Add phone dataContentprovideroperation Operation3 =contentprovideroperation. Newinsert (URI). Withvaluebackreference ("Raw_contact_id", 0). Withvalue ("MimeType", "VND.ANDROID.CURSOR.ITEM/PHONE_V2"). Withvalue ("Data2", "2"). Withvalue ("Data1", "0000000"). build ();    Operations.add (Operation3); Resolver.applybatch ("Com.android.contacts", operations);
3.Delete Core idea:(1) The ID is detected first in the Raw_contacts table based on the name (the DATA2 data of the name recorded here, not the data of data1), and (2) in data table as long as the raw_contact_id matches are deleted;
 Public voidTestdelete ()throwsexception{String name= "Xzdong"; //ID by nameUri uri = uri.parse ("Content://com.android.contacts/raw_contacts"); Contentresolver Resolver= This. GetContext (). Getcontentresolver (); Cursor Cursor= Resolver.query (URI,NewSTRING[]{DATA._ID}, "Display_name=?",NewString[]{name},NULL); if(Cursor.movetofirst ()) {intid = cursor.getint (0); //Delete corresponding data from the database by IDResolver.delete (URI, "Display_name=?",Newstring[]{name}); URI= Uri.parse ("Content://com.android.contacts/data"); Resolver.delete (URI,"Raw_contact_id=?",NewString[]{id+ ""}); }}
4.Update

Core idea:

(1) Do not need to update raw_contacts, only need to update the data table;

(2) Uri=content://com.android.contacts/data indicates the operation of the data table;

 Public voidTestupdate ()throwsexception{intID = 1; String Phone= "999999"; Uri URI= Uri.parse ("Content://com.android.contacts/data");//all data operations on the database tableContentresolver resolver = This. GetContext (). Getcontentresolver (); Contentvalues Values=Newcontentvalues (); Values.put ("Data1", phone); Resolver.update (URI, values,"Mimetype=?" And raw_contact_id=? ",Newstring[]{"Vnd.android.cursor.item/phone_v2", id+ ""}) }

Forwarded from: http://lichangsong.blog.51cto.com/7997447/1306033

Android Add, delete, change, check contacts in Contacts

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.