For reading contacts and writing data, social applications on the market often have this function
- Add an ID to the raw_contacts table
- Add the corresponding data to the database table
Gets the contentresolver object, via the getcontentresolver () method
Call the query () method of the contentresolver object , querying the raw_contacts table to get Cursor Object
Call the cursor object's movetolast () method, and the cursor moves to the last row
Gets the contact_idof the last row of records, the new ID is it plus 1
Call the contentresolver object's insert (uri,values) method, parameter:values is contentvalues Object put the new ID put () in
Gets the contentresolver object after the call to the Insert (uri,values) method, parameter:URI should be Data of the table Uri rules, contentvalues of the object, put (Key,value) ,"raw_contact_id" = the above ID,"mimetype" and "=" Vnd.android.cursor.item/phone_v2 "," data1 "=" Phone number "
And then add the name, just like above, in the contentvalues object,
Put "Mimietype" and "vnd.android.cursor.item/name" key value pairs
Public voidwritecontacts (View v) {contentresolver resolver=Getcontentresolver (); Uri URI=uri.parse ("Content://com.android.contacts/raw_contacts"); Uri Datauri=uri.parse ("Content://com.android.contacts/data"); //Find out the last IDCursor Cursor=resolver.query (URI,Newstring[]{"_id"},NULL,NULL,NULL); Cursor.movetolast (); intLastid=cursor.getint (0); intNewid=lastid+1; //Insert a Contact IDContentvalues values=Newcontentvalues (); Values.put ("CONTACT_ID", newId); Resolver.insert (URI, values); //inserting phone dataContentvalues datavalues=Newcontentvalues (); Datavalues.put ("RAW_CONTACT_ID", newId); Datavalues.put ("MimeType", "VND.ANDROID.CURSOR.ITEM/PHONE_V2"); Datavalues.put ("Data1", "110"); Resolver.insert (Datauri, datavalues); //Insert name DataContentvalues data1values=Newcontentvalues (); Data1values.put ("RAW_CONTACT_ID", newId); Data1values.put ("MimeType", "Vnd.android.cursor.item/name"); Data1values.put ("Data1", "Police1"); Resolver.insert (Datauri, data1values); Toast.maketext ( This, "Write contact succeeded", 0). Show (); }
[Android] Save contacts to System contacts