Android Learning notes: Accessing and adding contacts and contacts in Contacts database table introduction One

Source: Internet
Author: User

See the code directly, with detailed comments.
1. Location of the database file for the contact person
/data/data/com.android.providers.contacts/databases.contacts2.db

2. important tables in the database contacts table: This table holds all the phone contacts, one row for each contact, and the table holds the contact's contactid, Number of contacts,           Last contact time, whether it contains a number, whether it was added to the collection and other information. You can correspond to the field names of the table       understanding.
raw_contacts table: This table holds all created phone contacts, one for each contact, and a column in the list to see if the contact has been deleted. The table holds two Id:rawcontactid and ContactID, thereby linking the contacts table to the Raw_contacts table . The table holds the contact's Rawcontactid, ContactID, number of contacts, whether the last time the contact was added to the collection, the name displayed, and the phonetic alphabet used for sorting. mimetypes table: This table defines all the Mimetypeid, the unique flag for each field of the contact.

Data table:This table holds all the information for all created mobile phone contacts, one row per field, and the tabletwoId:mimetypei D and Rawcontactid were saved, thus the data table and theThe raw_contacts table is linked together. all information about the contact is saved in columns Data1 todata 15, and the contents of the columns are saved according toMimetypeid are different from each other. In the row of data that holds the number (mimetypeid=5),data1 Column Save number, data2 column save number type (mobile phone number/home number/work number, etc.).

Package Com.example.test;import Java.util.arraylist;import Android.content.contentprovideroperation;import Android.content.contentresolver;import Android.content.contenturis;import Android.content.contentvalues;import Android.database.cursor;import Android.net.uri;import Android.test.androidtestcase;import Android.util.Log;public Class Contactstest extends Androidtestcase {private static final String tag= "contactstest";p ublic void Testcontacts () thr OWS Exception//Test Query Contact {/* Content URI is a URI that identifies Provider data. The Content URI includes the entire Provider symbol name (authority) and the table name (path). The Content URI of the table is one of the parameters when a client-side method is invoked to access the Provider data table. Uri uri=uri.parse ("content://com.android.contacts/contacts"); *///The string com.android.contacts here is the authority part of Provider, and the string contacts is the path part of the data table. The string content://(scheme) must be specified to indicate that this is a content URI. Uri uri=uri.parse ("content://com.android.contacts/contacts"); Contentresolver Resolver=this.getcontext (). Getcontentresolver (); Cursor cursor=resolver.query (URI, new string[]{"_id"}, Null, NULL, NULL); while (Cursor.movetonext ()) {int contactid=cursor.getint (0); StringBuffer sb=new stringbuffer ("contactid="); Sb.append (ContactID); Uri=uri.parse ("content:// com.android.contacts/contacts/"+contactid+"/data ");/*cursor = Getcontentresolver (). Query (URI,//contact URI Mproject     Ion,//column mselectionclause to be returned,//Query condition Mselectionargs,//parameters of the query condition                    Msortorder); The ordering of the returned results requires */cursor datacursor=resolver.query (uri//Contact's URI, new string[]{"MimeType", "Data1", "Data2"}//the column to be returned, NULL Query conditions, null//parameters of the query condition, NULL);//The Order of the returned results requires while (Datacursor.movetonext ()) {String data=datacursor.getstring ( Datacursor.getcolumnindex ("data1")); String type=datacursor.getstring (Datacursor.getcolumnindex ("MimeType")), if ("Vnd.android.cursor.item/name"). Equals (type)) {Sb.append (", name=" +data);} else if ("Vnd.android.cursor.item/email_v2". Equals (Type)) {Sb.append (", email=" +data);} else if ("Vnd.android.cursor.item/phone_v2". Equals (Type)) {Sb.append (", phone=" +data);}} LOG.I (tag, sb.tostring ());} Cursor.close ();} public void Testcontactsnamebynumer () throws exception{string number= "15241499053";//provider provides access to a single record as long as the URI followed by an ID value. For example, to find a contact based on the phone, you only need to add number to it, and you can use the following Content Uri:uri uri=uri.parse ("content://com.android.contacts/data/phones/ filter/"+number); Contentresolver Resolver=this.getcontext (). Getcontentresolver (); Cursor cursor=resolver.query (URI, new string[]{"Display_name"}, NULL, NULL, NULL), while (Cursor.movetonext ()) {String Name=cursor.getstring (0); LOG.I (tag,name);} Cursor.close ();} /* Call the Contentresolver.insert () method to insert the data into the Provider. The method inserts a new row of data in Provider and returns a Content URI that points to the row data. The following code inserts a new contact in Com.android.contacts Provider: The data for the new row is stored in a Contentvalues object, which resembles a cursor that contains only one piece of data. The types of each field in the object can vary. If you do not need to specify a value, you can use the Contentvalues.putnull () method to null. The above code does not assign a value to the _ID field because the field is automatically maintained by the system.   Provider automatically assigns a unique value to the _id field of the inserted row and usually uses it as the primary key for the table. */public void Testaddcontacts () throws Exception{uri Uri=uri.parse ("Content://com.andrOid.contacts/raw_contacts "); Contentresolver Resolver=getcontext (). Getcontentresolver (); Contentvalues values=new contentvalues (); Long Contactid=contenturis.parseid (Resolver.insert (URI, values); uri= Uri.parse ("Content://com.android.contacts/data");//Add Name Values.put ("raw_contact_id", ContactID); Values.put (" MimeType "," Vnd.android.cursor.item/name "); Values.put (" Data2 "," Wang Chao "); Resolver.insert (URI, values);// Add Phone Values.put ("raw_contact_id", ContactID), Values.put ("MimeType", "vnd.android.cursor.item/phone_v2"); Values.put ("Data2", "2"), Values.put ("Data1", "4399101"); Resolver.insert (URI, values);//emailvalues.put ("Raw_ contact_id ", ContactID), Values.put (" MimeType "," Vnd.android.cursor.item/email_v2 "), Values.put (" Data2 "," 2 "); Values.put ("Data1", "[email protected]"); Resolver.insert (URI, values);} /* When developing an app, there are three other important forms of access to Provider: Bulk access: Through some methods of the Contentprovideroperation class, you can create bulk access tasks and pass Contentresolver.applybatch ( ) to submit. Asynchronous query: Executes a query in a separate thread. One solution is to use a Cursorloader object to implement it. An example is given in the guide loaders. Access data using Intent:Although you cannot send Intent directly to Provider, you can send Intent to Provider applications, which typically have the ability to modify Provider data. The following is a batch add through Contentprovideroperation. */public void TestAddContact2 () throws Exception{uri Uri=uri.parse ("content://com.android.contacts/raw_contacts"); Contentresolver Resolver=getcontext (). Getcontentresolver ();//Create an array of Contentprovideroperation objects and pass The Contentresolver.applybatch () method passes it to the Content Provider. Arraylist<contentprovideroperation> operations=new arraylist<contentprovideroperation> (); Contentprovideroperation Op1=contentprovideroperation.newinsert (URI). Withvalue ("account_name", null). Build (); O  Perations.add (OP1); */* does not specify a content URI at the time of invocation, but rather gives the authority of the content Provider. * Each Contentprovideroperation object in the array can operate on a different data table. * Contentresolver.applybatch () The returned result is also an array. */uri=uri.parse ("Ontent://com.android.contacts/data"); Contentprovideroperation Op2=contentprovideroperation.newinsert (URI). Withvaluebackreference ("raw_contact_id", 0) . Withvalue ("MimeType", "Vnd.android.cursor.item/namE "). Withvalue (" Data2 "," Bruce Lee "). Build (); Operations.add (OP2); Contentprovideroperation Op3=contentprovideroperation.newinsert (URI). Withvaluebackreference ("raw_contact_id", 0) . Withvalue ("MimeType", "Vnd.android.cursor.item/phone_v2"). Withvalue ("Data1", "110119"). Withvalue ("Data2", "2"). Build (); Operations.add (OP3); Contentprovideroperation Op4=contentprovideroperation.newinsert (URI). Withvaluebackreference ("raw_contact_id", 0) . Withvalue ("MimeType", "Vnd.android.cursor.item/email_v2"). Withvalue ("Data1", "[email protected]"). Withvalue ("Data2", "2"). Build (); Operations.add (OP4); Resolver.applybatch ("com.android.contacts", Operations);}}

Completing the above test code also requires you to add response permissions to the Contact table action.

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.example.contacts "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion=" "/> <application android:allowbackup=" True "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/app Theme "> <activity android:name=". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <uses-library android:name=" Android.test.runn Er "/> </application> <instrumentation android:name=" Android.test.InstrumentationTestRUnner "android:targetpackage=" com.example.contacts "></instrumentation><uses-permission android:name= "Android.permission.READ_CONTACTS"/><uses-permission android:name= "Android.permission.WRITE_CONTACTS"/ > "</manifest>

This is the appropriate permission for the contact operation:

<uses-permission android:name= "Android.permission.READ_CONTACTS"
/>
<uses-permission android:name= "Android.permission.WRITE_CONTACTS"
/>
This is the right and dependent library for the test unit:

<instrumentation android:name= "Android.test.InstrumentationTestRunner" android:targetpackage= " Com.example.contacts "></instrumentation>
<uses-library android:name= "Android.test.runner"/>

Android Learning notes: Accessing and adding contacts and contacts in Contacts database table introduction One

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.