AutoCompleteTextView with accented words

2

I'm having a hard time using AutoCompleteTextView with accented words.

For example:

I'm looking for bank branch names, by typing only ita the bank Itaú is finding, as shown below:

However,ifItypethelastuofthewordItaúwithouttheaccent,autocompletecannolongerfindit,asshownbelow:

Isthereanywaytoignoretheseaccentsandfindwhetherornottoplacetextwithaccents?

Note:I'malreadydoingwithcustomadapter,whichimplementsFilterable

Thefollowingisthecustomadaptercode:

publicclassHRArrayAdapter<T>extendsBaseAdapterimplementsFilterable{privateList<T>mObjects;privatefinalObjectmLock=newObject();privateintmResource;privateintmFieldId=0;privatebooleanmNotifyOnChange=true;privateContextmContext;privateArrayList<T>mOriginalValues;privateHRArrayFiltermFilter;privateLayoutInflatermInflater;publicHRArrayAdapter(Contextcontext,inttextViewResourceId){init(context,textViewResourceId,0,newArrayList<T>());}publicHRArrayAdapter(Contextcontext,intresource,inttextViewResourceId){init(context,resource,textViewResourceId,newArrayList<T>());}publicHRArrayAdapter(Contextcontext,inttextViewResourceId,T[]objects){init(context,textViewResourceId,0,Arrays.asList(objects));}publicHRArrayAdapter(Contextcontext,intresource,inttextViewResourceId,T[]objects){init(context,resource,textViewResourceId,Arrays.asList(objects));}publicHRArrayAdapter(Contextcontext,inttextViewResourceId,List<T>objects){init(context,textViewResourceId,0,objects);}publicHRArrayAdapter(Contextcontext,intresource,inttextViewResourceId,List<T>objects){init(context,resource,textViewResourceId,objects);}publicvoidadd(Tobject){if(mOriginalValues!=null){synchronized(mLock){mOriginalValues.add(object);if(mNotifyOnChange)notifyDataSetChanged();}}else{mObjects.add(object);if(mNotifyOnChange)notifyDataSetChanged();}}publicvoidinsert(Tobject,intindex){if(mOriginalValues!=null){synchronized(mLock){mOriginalValues.add(index,object);if(mNotifyOnChange)notifyDataSetChanged();}}else{mObjects.add(index,object);if(mNotifyOnChange)notifyDataSetChanged();}}publicvoidremove(Tobject){if(mOriginalValues!=null){synchronized(mLock){mOriginalValues.remove(object);}}else{mObjects.remove(object);}if(mNotifyOnChange)notifyDataSetChanged();}publicvoidclear(){if(mOriginalValues!=null){synchronized(mLock){mOriginalValues.clear();}}else{mObjects.clear();}if(mNotifyOnChange)notifyDataSetChanged();}publicvoidsort(Comparator<?superT>comparator){Collections.sort(mObjects,comparator);if(mNotifyOnChange)notifyDataSetChanged();}@OverridepublicvoidnotifyDataSetChanged(){super.notifyDataSetChanged();mNotifyOnChange=true;}publicvoidsetNotifyOnChange(booleannotifyOnChange){mNotifyOnChange=notifyOnChange;}privatevoidinit(Contextcontext,intresource,inttextViewResourceId,List<T>objects){mContext=context;mInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);mResource=mDropDownResource=resource;mObjects=objects;mFieldId=textViewResourceId;}publicContextgetContext(){returnmContext;}publicintgetCount(){returnmObjects.size();}publicTgetItem(intposition){returnmObjects.get(position);}publicintgetPosition(Titem){returnmObjects.indexOf(item);}publiclonggetItemId(intposition){returnposition;}publicViewgetView(intposition,ViewconvertView,ViewGroupparent){returncreateViewFromResource(position,convertView,parent,mResource);}privateViewcreateViewFromResource(intposition,ViewconvertView,ViewGroupparent,intresource){Viewview;TextViewtext;if(convertView==null){view=mInflater.inflate(resource,parent,false);}else{view=convertView;}try{if(mFieldId==0){//Ifnocustomfieldisassigned,assumethewholeresourceisaTextViewtext=(TextView)view;}else{//Otherwise,findtheTextViewfieldwithinthelayouttext=(TextView)view.findViewById(mFieldId);}}catch(ClassCastExceptione){Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
                throw new IllegalStateException(
                        "ArrayAdapter requires the resource ID to be a TextView", e);
            }

            text.setText(getItem(position).toString());

            return view;
        }


        public void setDropDownViewResource(int resource) {
            this.mDropDownResource = resource;
        }


        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return createViewFromResource(position, convertView, parent, mDropDownResource);
        }


        public static HRArrayAdapter<CharSequence> createFromResource(Context context,
                                                                                 int textArrayResId, int textViewResId) {
            CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
            return new HRArrayAdapter<CharSequence>(context, textViewResId, strings);
        }


        public HRArrayFilter getFilter() {
            if (mFilter == null) {
                mFilter = new HRArrayFilter();
            }
            return mFilter;
        }


        private class HRArrayFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence prefix) {
                FilterResults results = new FilterResults();

                if (mOriginalValues == null) {
                    synchronized (mLock) {
                        mOriginalValues = new ArrayList<T>(mObjects);
                    }
                }

                if (prefix == null || prefix.length() == 0) {
                    synchronized (mLock) {
                        ArrayList<T> list = new ArrayList<T>(mOriginalValues);
                        results.values = list;
                        results.count = list.size();
                    }
                } else {
                    String prefixString = prefix.toString().toLowerCase();

                    ArrayList<T> values = mOriginalValues;
                    final int count = values.size();

                    final ArrayList<T> newValues = new ArrayList<T>(count);
                    final ArrayList<String> strippedAccents = new ArrayList<String>();

                    for (int i = 0; i < count; i++) {
                        final T value = values.get(i);
                        final String valueText = value.toString().toLowerCase();
                        String valueTextNoPalatals = stripAccents(valueText);
                        String prefixStringNoPalatals = stripAccents(prefixString);

                        // First match against the whole, non-splitted value
                        if (valueText.startsWith(prefixString) || valueTextNoPalatals.startsWith(prefixStringNoPalatals)) {
                            newValues.add(value);
                        } else {
                            final String[] words = valueText.split(" ");
                            final int wordCount = words.length;

                            for (int k = 0; k < wordCount; k++) {
                                if (words[k].startsWith(prefixString)) {
                                    newValues.add(value);
                                    break;
                                }
                            }
                        }
                    }

                    results.values = newValues;
                    results.count = newValues.size();
                }

                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                //noinspection unchecked
                mObjects = (List<T>) results.values;
                if (results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        }

        private static Map<Character, Character> MAP_NORM;
        private static String stripAccents(String value) {

            if (MAP_NORM == null || MAP_NORM.size() == 0)
            {
                MAP_NORM = new HashMap<Character, Character>();
                MAP_NORM.put('À', 'A');
                MAP_NORM.put('Á', 'A');
                MAP_NORM.put('Â', 'A');
                MAP_NORM.put('Ã', 'A');
                MAP_NORM.put('Ä', 'A');
                MAP_NORM.put('È', 'E');
                MAP_NORM.put('É', 'E');
                MAP_NORM.put('Ê', 'E');
                MAP_NORM.put('Ë', 'E');
                MAP_NORM.put('Í', 'I');
                MAP_NORM.put('Ì', 'I');
                MAP_NORM.put('Î', 'I');
                MAP_NORM.put('Ï', 'I');
                MAP_NORM.put('Ù', 'U');
                MAP_NORM.put('Ú', 'U');
                MAP_NORM.put('Û', 'U');
                MAP_NORM.put('Ü', 'U');
                MAP_NORM.put('Ò', 'O');
                MAP_NORM.put('Ó', 'O');
                MAP_NORM.put('Ô', 'O');
                MAP_NORM.put('Õ', 'O');
                MAP_NORM.put('Ö', 'O');
                MAP_NORM.put('Ñ', 'N');
                MAP_NORM.put('Ç', 'C');
                MAP_NORM.put('ª', 'A');
                MAP_NORM.put('º', 'O');
                MAP_NORM.put('§', 'S');
                MAP_NORM.put('³', '3');
                MAP_NORM.put('²', '2');
                MAP_NORM.put('¹', '1');
                MAP_NORM.put('à', 'a');
                MAP_NORM.put('á', 'a');
                MAP_NORM.put('â', 'a');
                MAP_NORM.put('ã', 'a');
                MAP_NORM.put('ä', 'a');
                MAP_NORM.put('è', 'e');
                MAP_NORM.put('é', 'e');
                MAP_NORM.put('ê', 'e');
                MAP_NORM.put('ë', 'e');
                MAP_NORM.put('í', 'i');
                MAP_NORM.put('ì', 'i');
                MAP_NORM.put('î', 'i');
                MAP_NORM.put('ï', 'i');
                MAP_NORM.put('ù', 'u');
                MAP_NORM.put('ú', 'u');
                MAP_NORM.put('û', 'u');
                MAP_NORM.put('ü', 'u');
                MAP_NORM.put('ò', 'o');
                MAP_NORM.put('ó', 'o');
                MAP_NORM.put('ô', 'o');
                MAP_NORM.put('õ', 'o');
                MAP_NORM.put('ö', 'o');
                MAP_NORM.put('ñ', 'n');
                MAP_NORM.put('ç', 'c');
            }

            if (value == null) {
                return "";
            }

            StringBuilder sb = new StringBuilder(value);

            for(int i = 0; i < value.length(); i++) {
                Character c = MAP_NORM.get(sb.charAt(i));
                if(c != null) {
                    sb.setCharAt(i, c.charValue());
                }
            }

            return sb.toString();

        }

    }
    
asked by anonymous 20.04.2017 / 22:41

1 answer

3

Before making the comparison you can remove the String accents from your AutoCompleteTextView in the performFiltering() method, using for example the Normalizer:

System.out.println(Normalizer
                    .normalize("Itaú", Normalizer.Form.NFD)
                    .replaceAll("[^\p{ASCII}]", "")
                   );

Result:

  

Itau

See working at Ideone .

Source: Is there a way to get rid of accents and convert a whole string to regular letters?

    
24.04.2017 / 15:44