Get information about a phone contact

Source: Internet
Author: User

Using Contentresolver to get a phone contact, it is recommended to use the second

1. Generally the following method queries the table of views, table fields need to query fetch, more troublesome, may often error (especially when the real machine debugging)

//TODO This method directly specifies that the URI is not getting contact information in the real machine//[1] Get to content resolver//contentresolver contentresolver = Getcontentresolver ();                /*cursor cursor = contentresolver.query (Uri. Parse ("Content://com.android.contacts/raw_contacts"),                New string[] {"contact_id"}, NULL, NULL, NULL); while (Cursor.movetonext ()) {//have content, get//[2] get to contact_id String contact_id = curs                    Or.getstring (0); [3] According to the obtained CONTACT_ID to query data table, data1,mimetype_id field data//# #虽然data表中的字段是mimetype_id, but to use mimetype to get To the data, corresponding to the fields of the mimetypes table Cursor Cursor2 = Contentresolver.query (Uri.parse ("Con                            Tent://com.android.contacts/data "), new string[] {" Data1 "," MimeType "},                                        "Raw_contact_id=?", new string[] {contact_id}, NULL); Create collection HashMap, which stores the name and number of the contact, populates the ListView with Data hashmap<string, string> contactsmap=new hashmap<st                    Ring, string> (); While(Cursor2.movetonext ())                        {//[4] gets to data1,mimetype_id String data1 = cursor2.getstring (0);                        String type = cursor2.getstring (1);                            if (Type.equals ("Vnd.android.cursor.item/phone_v2")) {//data1 is phone number//Save data if (!                            Textutils.isempty (data1)) {contactsmap.put ("phone", data1);                        }else{contactsmap.put ("phone", "null");//If it is empty} }else if (type.equals ("Vnd.android.cursor.item/name")) {//data1 Contact name if (!                            Textutils.isempty (data1)) {contactsmap.put ("name", data1);                        }else{contactsmap.put ("name", "null");//If it is empty} }}//Loop once TimAdd a group of contact data Contactslist.add (CONTACTSMAP); }*/

2. Directly using the API to provide encapsulated class Contactscontract for URI and field acquisition will be simple point, generally not error-prone, debugging in the real machine is very useful

Contentresolver Contentresolver =Getcontentresolver (); Cursor Cursor=contentresolver.query (ContactsContract.CommonDataKinds.Phone.CONTENT_URI,Newstring[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.DATA1},NULL,NULL,NULL);  while(Cursor.movetonext ()) {HashMap<string, string> hashmap=NewHashmap<string, string>(); Hashmap.put ("Name", cursor.getstring (0)); Hashmap.put ("Phone", cursor.getstring (1));//log.i ("Phone", cursor.getstring (0));//log.i ("Phone", cursor.getstring (1));Contactslist.add (HASHMAP); }

Here is the entire activity code:

 Packagecom.itlearn.contacts;Importjava.util.ArrayList;ImportJava.util.HashMap;ImportAndroid.content.ContentResolver;ImportAndroid.database.Cursor;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.provider.ContactsContract;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.BaseAdapter;ImportAndroid.widget.ListView;ImportAndroid.widget.TextView; Public classMainactivityextendsactionbaractivity {PrivateListView lv_contacts; //a single-column collection of stored contact information stored in the map collection (name and number)ArraylistNewArraylist();  PublicHandler mhandler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); Lv_contacts.setadapter (NewListcontactsadapter ());    }            }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Lv_contacts=(ListView) Findviewbyid (r.id.lv_contacts);    Initui (); }    Private voidInitui () {NewThread (NewRunnable () {@Override Public voidrun () {contentresolver contentresolver=Getcontentresolver (); Cursor Cursor=contentresolver.query (ContactsContract.CommonDataKinds.Phone.CONTENT_URI,Newstring[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.DATA1},NULL,NULL,NULL);  while(Cursor.movetonext ()) {HashMap<string, string> hashmap=NewHashmap<string, string>(); Hashmap.put ("Name", cursor.getstring (0)); Hashmap.put ("PhoneNumber", cursor.getstring (1));//log.i ("Phone", cursor.getstring (0));//log.i ("Phone", cursor.getstring (1));Mcontactsarraylist.add (HASHMAP); }                //sending messages for UI updatesMhandler.sendemptymessage (0);    }}). Start (); }    Private classListcontactsadapterextendsbaseadapter{@Override Public intGetCount () {returnmcontactsarraylist.size (); } @Override PublicHashmap<string,string> GetItem (intposition) {            returnMcontactsarraylist.get (position); } @Override Public LongGetitemid (intposition) {            returnposition; } @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {View View= View.inflate (Getapplicationcontext (), R.layout.listview_contact_item,NULL); //gets the ID that needs to be displayed in the layout for name and PhoneNumberTextView tv_name=(TextView) View.findviewbyid (r.id.tv_name); TextView Tv_phonenumber=(TextView) View.findviewbyid (R.id.tv_phonenumber); Tv_name.settext (GetItem (position). Get ("Name")); Tv_phonenumber.settext (GetItem (position). Get ("PhoneNumber"). Replace ("", ""). Replace ("-", ""). Trim ()); returnview; }} @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {intID =Item.getitemid (); if(id = =r.id.action_settings) {            return true; }        return Super. onoptionsitemselected (item); }}

Layout file:

Activity_main.xml

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "Com.itlearn.contacts.MainActivity" > <TextView Android:id= "@+id/tv_title"Android:text= "Contact List"android:textsize= "20SP"Android:textcolor= "#FFF"android:padding= "15SP"Android:background= "#222222"android:gravity= "Center"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"/> <!--contact List Display <ListView Android:id= "@+id/lv_contacts"Android:layout_below= "@+id/tv_title"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" ></ListView></RelativeLayout>

Listview_contacts_item:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:padding= "10DP"android:orientation= "Vertical" > <TextView Android:id= "@+id/tv_name"Android:textcolor= "#23350B"android:textsize= "20DP"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"/> <TextView Android:id= "@+id/tv_phonenumber"Android:paddingtop= "3DP"Android:paddingbottom= "1DP"Android:textcolor= "#C3010A"android:textsize= "16DP"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"/></linearlayout>

Operation Result:

Get information about a phone contact

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.