Android Contacts Fuzzy query search (number, name, initial spelling, full spell), bulk select contacts

Source: Internet
Author: User

Android Contacts fuzzy query search (number, name, initial spelling, all-in-one), bulk select contacts

The company's recent projects encountered a need to read contact contacts, and need to support the contact of Fuzzy query and batch selection, the Internet to find a few examples, fuzzy query this piece of processing is a little flaw, Finally, I have made the optimization on the basis of the hard contribution of the netizens, and finally make a fuzzy query of the contact person. The following features are supported:


1. By number, name, the first letter simple spell, the whole puzzle fuzzy query
2. Support [A-z] Quick navigation
3. Support Contacts by first letter category
4. Support contact Batch selection.

specific GitHub address: https://github.com/cuixbo/FuzzyQueryContacts
The interface is as follows:


Code structure:

Main code:
Contactsactivity:
Package Com.xbc.utils.activity;import Java.util.arraylist;import Java.util.collections;import java.util.List; Import Java.util.locale;import Android.app.activity;import Android.content.contentresolver;import Android.database.cursor;import Android.os.bundle;import Android.provider.ContactsContract.CommonDataKinds.Phone; Import Android.text.editable;import android.text.textutils;import Android.text.textwatcher;import Android.util.Log ; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.edittext;import Android.widget.ImageView; Import Android.widget.listview;import Android.widget.textview;import Android.widget.toast;import Com.xbc.contacts.r;import Com.xbc.utils.activity.contactssortadapter.viewholder;import Com.xbc.utils.activity.sidebar.ontouchingletterchangedlistener;public class Contactsactivity extends activity { ListView Mlistview; EditText Etsearch;imageview IvclearText;private SideBar sidebar;private TextView dialog;private list<sortmodel> mallcontactslist;private Contactssortadapter adapter;/** * Kanji convert to Pinyin class */private Characterparser characterparser;/** * Sort the data class in the ListView according to Pinyin */ Private Pinyincomparator pinyincomparator; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.layout_contacts); init ();} private void Init () {Initview (); Initlistener (); Loadcontacts ();} private void Initlistener () {/** clears the input character **/ivcleartext.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {etsearch.settext ("");}}); Etsearch.addtextchangedlistener (New Textwatcher () {@Overridepublic void ontextchanged (charsequence arg0, int arg1, int arg2, int arg3) {} @Overridepublic void beforetextchanged (charsequence arg0, int arg1, int arg2, int arg3) {} @Overridepubli c void Aftertextchanged (Editable e) {String content = Etsearch.gettext (). toString (); if ("". Equals (content)) { Ivcleartext.setvisIbility (view.invisible);} else {ivcleartext.setvisibility (view.visible);} if (content.length () > 0) {arraylist<sortmodel> fileterlist = (arraylist<sortmodel>) search (content); Adapter.updatelistview (fileterlist);//madapter.updatedata (mcontacts);} else {Adapter.updatelistview (mallcontactslist);} Mlistview.setselection (0);}); /Set right [A-z] Quick nav Bar Touch Monitor Sidebar.setontouchingletterchangedlistener (new Ontouchingletterchangedlistener () {@ overridepublic void ontouchingletterchanged (String s) {//The first occurrence of the letter in the position int position = Adapter.getpositionforsection ( S.charat (0)); if (position! = 1) {mlistview.setselection (position);}}); Mlistview.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> Adapterview, view view, int position, long arg3) {Viewholder Viewholder = (viewholder) view.gettag (); viewholder.cbchecked . PerformClick (); adapter.togglechecked (position);}}); private void Initview () {SideBar = (SideBar) Findviewbyid (r.id.sidrbar);d Ialog = (textvIew) Findviewbyid (R.id.dialog); Sidebar.settextview (dialog); ivcleartext = (ImageView) Findviewbyid (r.id.ivcleartext ); etsearch = (EditText) Findviewbyid (r.id.et_search); Mlistview = (ListView) Findviewbyid (r.id.lv_contacts);/** Set Adapter **/characterparser = Characterparser.getinstance () to the ListView; mallcontactslist = new Arraylist<sortmodel > ();p inyincomparator = new Pinyincomparator (); Collections.sort (Mallcontactslist, pinyincomparator);//Sort source data according to A-Z adapter = new Contactssortadapter (This, mallcontactslist); Mlistview.setadapter (adapter);} private void Loadcontacts () {New Thread (new Runnable () {@Overridepublic void run () {try {contentresolver resolver = Getapp Licationcontext (). Getcontentresolver (); Cursor phonecursor = Resolver.query (Phone.content_uri, new string[] {phone.display_name, phone.number, "Sort_key"}, nul L, NULL, "Sort_key COLLATE localized ASC"); if (phonecursor = = NULL | | Phonecursor.getcount () = = 0) {Toast.maketext (getappl Icationcontext (), "No Read contact permission or contact data not obtained", TOAST.LEngth_short). Show (); return;} int phones_number_index = Phonecursor.getcolumnindex (phone.number); int phones_display_name_index = Phonecursor.getcolumnindex (phone.display_name); int sort_key_index = Phonecursor.getcolumnindex ("SORT_KEY"); if ( Phonecursor.getcount () > 0) {mallcontactslist = new arraylist<sortmodel> (); while (Phonecursor.movetonext ()) { String PhoneNumber = phonecursor.getstring (Phones_number_index), if (Textutils.isempty (PhoneNumber)) continue; String contactName = phonecursor.getstring (Phones_display_name_index); String SortKey = phonecursor.getstring (Sort_key_index);//system.out.println (SortKey); Sortmodel Sortmodel = new Sortmodel (ContactName, PhoneNumber, SortKey);//priority to use System SortKey fetch, not to use tool fetch string sortletters = Getsortletterbysortkey (SortKey); if (sortletters = = null) {sortletters = Getsortletter (contactName);} Sortmodel.sortletters = Sortletters;sortmodel.sorttoken = Parsesortkey (SortKey); Mallcontactslist.add (SortModel);}} Phonecursor.close (); Runonuithread (new Runnable (){public void Run () {Collections.sort (mallcontactslist, Pinyincomparator); Adapter.updatelistview (mallcontactslist);}});} catch (Exception e) {log.e ("Xbc", E.getlocalizedmessage ());}}). Start ();} /** * name to Pinyin, take the initials * @param name * @return */private string Getsortletter (string name) {String letter = "#"; if (name = = NULL ) {return letter;} Kanji converted to pinyin string pinyin = characterparser.getselling (name); String sortstring = pinyin.substring (0, 1). toUpperCase (Locale.chinese);//Regular expression to determine if the first letter is an English letter if (Sortstring.matches (" [A-z] ")) {letter = Sortstring.touppercase (Locale.chinese);} return letter;} /** * Take Sort_key's initials * @param SortKey * @return */private string Getsortletterbysortkey (String sortKey) {if (SortKey = = nul L | | "". Equals (Sortkey.trim ())) {return null;} String letter = "#";//Kanji converted to pinyin string sortstring = Sortkey.trim (). substring (0, 1). toUpperCase (Locale.chinese);//Regular expression, Determine if the first letter is an English letter if (Sortstring.matches ("[A-z]")) {letters = Sortstring.touppercase (Locale.chinese);} return letter;} /** * Fuzzy query * @param str* @return */private list<sortmodel> search (String str) {list<sortmodel> filterlist = new arraylist< Sortmodel> ();//Filtered ListIf (str.matches ("^ [0-9]|[ /+]) (*$ ")) {//Regular expression match number for (Sortmodel contact:mallcontactslist) {if (Contact.number! = NULL && contact.name! = N ull) {if (Contact.number.contains (str) | | contact.name.contains (str)) {if (!filterlist.contains (contact)) { Filterlist.add (contact);}}}} else {for (Sortmodel contact:mallcontactslist) {if (Contact.number! = NULL && Contact.name! = null) {//name full match, first name Alphabetical match, name full letter match if (Contact.name.toLowerCase (Locale.chinese). Contains (Str.tolowercase (Locale.chinese)) | | Contact.sortKey.toLowerCase (Locale.chinese). Replace ("", ""). Contains (Str.tolowercase (Locale.chinese)) | | Contact.sortToken.simpleSpell.toLowerCase (Locale.chinese). Contains (Str.tolowercase (Locale.chinese)) | | Contact.sortToken.wholeSpell.toLowerCase (Locale.chinese). Contains (Str.tolowercase (Locale.chinese))) {if (! Filterlist.contains (Contact)) {FilterList.add (contact);}}}} return filterlist;} String Chreg = "[\\u4e00-\\u9fa5]+";//Chinese string matching//string chreg= "[^\\u4e00-\\u9fa5]";//except Chinese characters match/** * Parse Sort_key, package simple spell, full spell * @param sortKey * @return */public sorttoken parsesortkey (String sortKey) {Sorttoken token = new Sorttoken (); if (SortKey  ! = null && sortkey.length () > 0) {//contains Chinese characters string[] enstrs = Sortkey.replace ("", ""). Split (Chreg); for (int i = 0, length = enstrs.length; i < length; i++) {if (enstrs[i].length () > 0) {//stitching Jane Token.simplespell + + enstrs[i].charat (0); Token.wholespell + = Enstrs[i];}}} return token;}}


Android Contacts Fuzzy query search (number, name, initial spelling, full spell), bulk select contacts

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.