How to get Android phone contacts and show them by Alphabet (i)

Source: Internet
Author: User

Android provides a query URI for the local database that can be queried for data:

The use of a asyncqueryhandler to query, Asyncqueryhandler himself opened a thread for data query, very convenient


Protected Asyncqueryhandler mqueryhandler;protected final void querypersonal () {Mqueryhandler.startquery (QUERY_TOKEN , NULL, ContactsContract.Contacts.CONTENT_URI, personal.contacts_summary_projection, NULL, NULL, Getsortorder ( ContactsContract.Contacts.DISPLAY_NAME));} protected static string Getsortorder (String fieldName) {//substr is the Intercept function, taking the first letter//collate is primarily used to rank characters//collate localized Sort by local language return "case when substr (UPPER (" + FieldName + "), 1, 1) between ' A ' and ' Z ' then 1 else ten END," +fieldname + " COLLATE localized ASC ";} Protected final class MyHandler extends Asyncqueryhandler {/** * Asynchronous Query handler constructor. */public Myhandl ER (context context) {super (Context.getcontentresolver ());} /** * on query completion. */@Override <strong>protected void onquerycomplete (int token, Object cookie, cursor cursor) </strong>{// Handler query completed callback if (cursor = = NULL | | cursor.isclosed ()) {return;} if (!isfinishing ()) {setloading (false); if (madapter! = null) {madapter.setloading (FALSE); madapter.changecursor (cursor);} if (cursor.getcount () = = 0) {memtytext.setvisibility (view.visible);} else {memtytext.setvisibility (view.invisible);}} else {if (cursor! = NULL &&!cursor.isclosed ()) {cursor.close ();}}}}

This layout is:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:rcm=" Http://schemas.android.com/apk/res/com.ringcentral.android "android:id=" @+id/contact_list_ View "android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @color/bgcolor Main "android:orientation=" vertical "> <listview android:id=" @android: Id/list "Android:layout_wid        Th= "Match_parent" android:layout_height= "match_parent" android:cachecolorhint= "@android: Color/transparent" Android:descendantfocusability= "afterdescendants" android:divider= "@null" android:fastscrollenabled= "t Rue "android:listselector=" @drawable/bg_list_item_selector "/> <relativelayout android:id=" @+id/no_ Contact_indication "android:layout_width=" match_parent "android:layout_height=" Match_parent "> < TextView android:id= "@+id/emptYlisttext "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Andro Id:layout_centerinparent= "true" android:singleline= "true" android:text= "No Contacts" Android Oid:textcolor= "@color/text_no_items" android:textsize= "20sp"/> <progressbar android:id = "@+id/loading" style= "@style/rcmprogressbar" android:layout_width= "Wrap_content" Android    : layout_height= "Wrap_content" android:layout_centerinparent= "true" android:visibility= "Gone"/> </RelativeLayout></LinearLayout>

Then the list adapter is written:

Protected static Final class Sectionedcontactlistitemcache {public TextView sectionheader;public TextView Nameview;        Public TextView typeview;public ImageView photoview;public ImageView Detailitemicon; <span style= "White-space:pre" ></span>public View Nametypewrapper;} Protected final class Contactsadapter extends Resourcecursoradapter {public Contactsadapter (context context) {Super ( context, r.layout.contacts_list_item_photo,null);} @Overridepublic void Changecursor (Cursor c) {super.changecursor (c);} Protected string GetTitle (String displayName) {string title;/** Check if the first letter is 中文版 letter */matcher MATC her = Mpattern.matcher (DisplayName), if (!matcher.find ()) {title = None_english_letter_title;} else {title = Displayname.trim (). substring (0, 1). toUpperCase (locale.us);} return title;} Protected string GetDisplayName (Cursor c) {String displayName = c.getstring (Personal.name_column_index); Textutils.isempty (DisplayName)) {return "";} return displayName;} @Overridepublic void BindView (view view, context context, cursor cursor) {final Sectionedcontactlistitemcache cache = (Sectione Dcontactlistitemcache) View.gettag (); cache.typeView.setVisibility (View.gone); Cache.photoView.setVisibility ( view.visible); String name = cursor.getstring (Personal.name_column_index), if (Textutils.isempty (name)) {Cache.nameView.setText ( R.string.contact_no_name);} else {cache.nameView.setText (name);}}  @Overridepublic View Newview (context context, cursor cursor, viewgroup parent) {View view = Super.newview (context, cursor,            parent); final Sectionedcontactlistitemcache cache = new Sectionedcontactlistitemcache (); Cache.nametypewrapper = View.findviewbyid (r.id.name_type); cache.sectionheader = (TextView) View.findviewbyid ( R.id.txtsectionheader); Cache.nameview = (TextView) View.findviewbyid (r.id.name); Cache.typeview = (TextView) View.findviewbyid (r.id.type); Cache.photoview = (ImageView) View.findviewbyid (r.id.photo); Cache.detailitemicon = ( ImageView) view.findviewbyiD (R.id.contacts_detail_item_icon); View.settag (cache); return view;}} End of Adapter

Item Adapter Layout:

<?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=" wrap_content "android:orientation=" vertical "&    Gt <textview android:id= "@+id/txtsectionheader" android:layout_width= "Match_parent" android:layout_he ight= "@dimen/list_item_section_height" android:background= "@drawable/bg_contacts_section_header" Android:gra Vity= "Center_vertical|left" android:paddingleft= "@dimen/default_padding_to_side" android:textcolor= "@color/C Ontacts_text_separator_text_color "android:textsize=" @dimen/font_size_medium "/> <relativelayout an Droid:id= "@+id/contact_item" android:layout_width= "match_parent" android:layout_height= "@dimen/general_list_ View_item_height "> <imageview android:id=" @+id/photo "android:layout_width=" @dimen/favo   Rites_item_picture_width "         android:layout_height= "Match_parent" android:layout_alignparentleft= "true" android:layout_a Lignwithparentifmissing= "true" android:paddingtop= "6DP" android:paddingbottom= "6DP" Andro        id:layout_marginleft= "@dimen/contact_photo_margin_left_right" android:scaletype= "Fitcenter"/> <!--This icon is added in next version, and now it would is hidden---<imageview and            Roid:id= "@+id/contacts_detail_item_icon" android:layout_width= "50dip" android:layout_height= "60dip" Android:layout_alignparentright= "true" android:layout_marginright= "0dip" Android:croptopa Dding= "true" android:duplicateparentstate= "false" android:paddingbottom= "3dip" Android:pa ddingtop= "3dip" android:scaletype= "Fitcenter" android:src= "@drawable/ic_list_link" Androi D:visibility= "Gone"/> <relativelayout android:id= "@+id/name_type" android:layout_width= "Match_parent" Androi d:layout_height= "Match_parent" android:layout_alignwithparentifmissing= "true" Android:layout_tolefto            f= "@id/contacts_detail_item_icon" android:layout_marginleft= "@dimen/contact_photo_margin_left_right" android:layout_torightof= "@id/photo" android:background= "@drawable/bg_list_item_divider" > <te Xtview android:id= "@+id/type" android:layout_width= "Wrap_content" Android:lay out_height= "Wrap_content" android:layout_alignbaseline= "@+id/name" Android:layout_alignparen Tright= "true" android:layout_marginright= "@dimen/contact_type_margin_left_right" Android:ell                Ipsize= "marquee" android:gravity= "Center_vertical|right" android:singleline= "true" Android:tExtcolor= "@color/refresh_control_text_color" android:textsize= "@dimen/font_size_small"/> &lt ; TextView android:id= "@+id/name" android:layout_width= "Match_parent" android:l ayout_height= "Wrap_content" android:layout_centervertical= "true" android:layout_marginright= "@dimen/contact_name_margin_left_right" android:layout_toleftof= "@id/type" android:ellipsize = "marquee" android:gravity= "Center_vertical|left" android:singleline= "true" a Ndroid:textcolor= "@color/text_color_main" android:textsize= "@dimen/font_size_medium"/> </rela Tivelayout> </RelativeLayout></LinearLayout>


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.