Android instance-Mobile security Defender (26)-Get Phone contact information

Source: Internet
Author: User

First, the goal.

Get phone contact information from the content parser and display it in a custom style.

For ease of introduction and reuse, re-establish a "read contact" project.

Second, the code implementation.

1, the new project, named "Read Contact." In the layout file (Activity_main.xml), the ListView component (whose ID is select_contact) is used.

Layout file Code:

  1  <relativelayout xmlns:android= "Http://schemas.android.com/apk/res /android " xmlns:tools=" Http://schemas.android.com/tools " 3  android:layout_width= "match_parent"  4  android:layout_height=" match _parent " tools:context=". Mainactivity "> 6   7  <listview   8  android:id=" @+id/select_contact " 9  android:layout_width= "wrap_content" 10  Android:layout_heigh t= "Wrap_content"/>11  12  </ Relativelayout> 
View Code

2. Instantiate the ListView component (named Select_contact) in the main program and find the ListView object in the layout file through the Findviewbyid () method. The Select_contact object needs to populate the relevant data through the adapter's method (Setadapter (ListAdapter adapter)), where ListAdapter adapter takes Simpleadapter ( Context context, list<? Extends Map<string,?>> data, int resource, string[] from, int[] to). The second parameter in the Simpleadapter list is the data that needs to be displayed, so a custom method (named Getcontactinfo ()) is needed to get the contact information from the phone and form a list collection.

3, in the main program to get a new phone contact information method (named Getcontactinfo ()), the return value type is list<map<string, string>>. In this method:

①. Get a Content parser (Contentresolver) object by Getcontentresolver (), named (resolver). You need to get permission (Android.permission.READ_CONTACTS) because you need to read the phone contact.

②. Using the Content Parser's query (URI URI, string[] projection, string selection, string[] Selectionargs, string sortOrder) method to find the relevant data in the contact data in the phone, the URI of the parameter is the URI address of the database that needs to be queried, string[] projection is the column name that needs to be returned, String selection is the query condition, string[] Selectionargs is the query condition parameter, String SortOrder is ordered. The return value of the method is the cursor object, which resembles a table with the number of columns equal to the number of query criteria and the number of rows equal to the number of rows of data in the database that match the query criteria, which needs to be closed in a timely manner after the object is used.

③. In this example, you need to query the Raw_contacts table in the contact data with a URI of "content://com.android.contacts/raw_contacts" and a data table with a URI of "content:// Com.android.contacts/data "). In the Raw_contacts table, query the column named "Contact_id", which holds the IDs of all the contacts. Then through the while loop to determine whether the queried cursor object has the next, if any, is obtained through the getstring (int columnindex) method. Because there is only one query condition, the cursor object has only one column, so the parameters in the GetString method can only be 0, and note that the parameter refers to the column's Corner label.

④ according to each of the IDs identified whether it is empty, not empty then through the Content Parser Query method querying the data table, you need to query the column named "Data1" and "mimetype", the query conditions and parameters are contact_id and its value. The cursor object queried by the while loop is also next, if any, the data inside the cursor object is obtained through the getstring (int columnindex) method, where the first column is the DATA1 data and the second column is the mimetype data.

⑤. Depending on the value of the mimetype data, the equal method determines whether the obtained data is a contact name or a phone number, and if its value is "Vnd.android.cursor.item/name", the data obtained is data1 as the contact name, if the value is " Vnd.android.cursor.item/phone_v2 ", then get the data data1 as the contact phone.

⑥. In the new Method Getcontactinfo (), create a new list<map<string, a string>> list object that stores all the contact information that was taken out. A new map<string, String> object, used to store a contact's "name" and "Phone" information (note that both the list object and the map object are of the interface type) are created by using the IF statement to determine that the ID is not empty after the fourth step. Then, in the fifth step, you decide whether the data will be the contact name or the phone and put it into the map object.

⑦. After a contact information is placed in a map object, the map object is placed in the Contact list object by the Add method, and the list object is returned.

New method to get phone contact information (named Getcontactinfo ()) Code:

1 PrivateList<map<string, string>>Getcontactinfo () {2         //Get content Parser3Contentresolver resolver =getcontentresolver ();4list<map<string, string>> listcontacts =NewArraylist<map<string,string>>();5         //gets the URI of the related table for the phone contact database6Uri uri = uri.parse ("Content://com.android.contacts/raw_contacts");7Uri uridata = Uri.parse ("Content://com.android.contacts/data");8         //querying related data in a data table9cursor cursor = resolver.query (URI,NewString[] {"contact_id" },Ten                 NULL,NULL,NULL); One          while(Cursor.movetonext ()) { AString contact_id = cursor.getstring (0); -             if(contact_id! =NULL) { -                 //A specific contact person theMap<string,string> mapcontact =NewHashmap<string, string>(); -Cursor datacursor = Resolver.query (Uridata,Newstring[] { -"Data1", "MimeType"}, "Contact_id=?", -                         NewString[] {contact_id},NULL); +                  while(Datacursor.movetonext ()) { -String data1 = datacursor.getstring (0); +String mimetype = datacursor.getstring (1); A                     if("Vnd.android.cursor.item/name". Equals (MimeType)) { at                         //Name of contact person -Mapcontact.put ("name", data1); -}Else if("Vnd.android.cursor.item/phone_v2". Equals (MimeType)) { -                         //phone number of the contact person -Mapcontact.put ("Phone", data1); -                     } in                 } -                 //put each contact in a list object to Listcontacts.add (mapcontact); +                 //close the Cursor object - datacursor.close (); the             } *         } $         //close the Cursor objectPanax Notoginseng cursor.close (); -         returnlistcontacts; the}
View Code

4, in the main method through the Setadapter (ListAdapter adapter) method for the main layout file loading data and a single data display style.

①. Create a new XML file in the Layout folder to create a single data display style. Text display format, size, arrangement, etc. can be customized.

XML file code for a single data display style:

1<?xml version= "1.0" encoding= "Utf-8"?>2<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"3Android:layout_width= "Match_parent"4android:layout_height= "Match_parent"5android:orientation= "Vertical" >6 7<TextView8Android:id= "@+id/contact_item_name"9Android:layout_width= "Match_parent"Tenandroid:layout_height= "Wrap_content" Oneandroid:text= "Name" AAndroid:textsize= "22SP"/> -      -<TextView theAndroid:id= "@+id/contact_item_phone" -Android:layout_width= "Match_parent" -android:layout_height= "Wrap_content" -android:text= "Phone number"/> +  -</LinearLayout>
View Code

②. Because the ListAdapter object is an interface, new subclasses Simple Adapter (context context, List<? extends Map< String ,?>> data, int resource, String [] From, int[] to), the first parameter in the method is the context (this is this), the second parameter is the data that needs to be displayed (that is, the contact's list object), and the third parameter is the ID of the style that the individual data wants to display (that is, contact_item_ The ID of the view), the fourth parameter and the fifth parameter represent the corresponding relationship (all in the form of an array) of one of the data in the data to be displayed and the position to be displayed in the style.

Android instance-Mobile security Defender (26)-Get Phone contact information

Related Article

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.