Thursday, January 14, 2016

Auto Complete TextView (with history as suggestion) in android

Auto Complete TextViews


An editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.
The drop down can be dismissed at any time by pressing the back key or, if no item is selected in the drop down, by pressing the enter/dpad center key.

The list of suggestions is obtained from a data adapter and appears only after a given number of characters defined by the threshold.
The following code snippet shows how to create a text view which suggests various countries names while the user is typing:
 
 
 public class CountriesActivity extends Activity {
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.countries);

         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                 android.R.layout.simple_dropdown_item_1line, COUNTRIES);
         AutoCompleteTextView textView = (AutoCompleteTextView)
                 findViewById(R.id.countries_list);
         textView.setAdapter(adapter);
     }

     private static final String[] COUNTRIES = new String[] {
         "Belgium", "France", "Italy", "Germany", "Spain"
     };
 }
 
 
 

Auto Complete TextView (with history as suggestion):

->use HistoryAutoCompleteTextView class instead of AutocompleteTextView

  
public class HistoryAutoCompleteTextView extends AutoCompleteTextView
{
    String history="";


    public History_AutoCompleteTextView(Context context)
    {
        super(context);
        setHistoryHolderAdapter(context);
        this.setThreshold(1);
    }

    public History_AutoCompleteTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        setHistoryHolderAdapter(context);
        this.setThreshold(1);
    }

    public History_AutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        setHistoryHolderAdapter(context);
        this.setThreshold(1);
    }

    @Override
    public <T extends ListAdapter & Filterable> void setAdapter(T adapter)
    {
        super.setAdapter(adapter);
    }

    public void setHistoryHolderAdapter(Context con)
    {
        this.setAdapter(new Search_history_adapter(con, android.R.layout.simple_list_item_1));
    }


    public void saveSearch(Context con)
    {
        this.setThreshold(1);

        SharedPreferences sp;
        SharedPreferences.Editor editor;
        sp = con.getSharedPreferences("search", Activity.MODE_PRIVATE);
        editor = sp.edit();

        history = sp.getString("history", "");

        List<String> history_list = new ArrayList<>();

        history_list = Arrays.asList(history.split("\\s*,\\s*"));

        boolean hasALready=false;
        for (int i = 0; i < history_list.size(); i++)
        {
            if(history_list.get(i).equalsIgnoreCase(this.getText().toString()))
            {
                hasALready = true;
            }
        }

        if(!hasALready)
        {
            if (history.equals(""))
            {
                history = this.getText().toString().trim();
                editor.putString("history", history);
            }
            else
            {
                history = history + "," + this.getText().toString().trim();
                editor.putString("history", history);
            }
            editor.commit();
        }
    }

    public void clearSearch_history(Context con)
    {
        SharedPreferences sp;
        SharedPreferences.Editor editor;
        sp = con.getSharedPreferences("search", Activity.MODE_PRIVATE);
        editor = sp.edit();

        editor.clear();
        editor.commit();
    }






    public class Search_history_adapter extends ArrayAdapter<String> implements Filterable
    {
        public List<String> history_list = new ArrayList<>();

        List<String> history_listG = new ArrayList<>();

        private Context con;

        SharedPreferences sp;

        public Search_history_adapter(Context context, int textViewResourceId)
        {
            super(context, textViewResourceId);
            con = context;
        }

        @Override
        public int getCount()
        {
            return history_listG.size();
        }

        @Override
        public String getItem(int index)
        {
            try
            {
                return history_listG.get(index);
            }
            catch (Exception e)
            {
            }
            return "";
        }

        String history = "";

        @Override
        public Filter getFilter()
        {
            Filter filter = new Filter()
            {
                @Override
                protected FilterResults performFiltering(final CharSequence constraint)
                {
                    SharedPreferences        sp;
                    SharedPreferences.Editor editor;
                    sp = con.getSharedPreferences("search", Activity.MODE_PRIVATE);

                    FilterResults filterResults = new FilterResults();
                    if (constraint != null)
                    {
                        Log.e("CONSTRAINT", constraint.toString());

                        history = sp.getString("history", "");

                        history_list = Arrays.asList(history.split("\\s*,\\s*"));

                        history_listG.clear();

                        for (int i = 0; i < history_list.size(); i++)
                        {
                            String value = history_list.get(i);

                            if (value.contains(constraint))
                            {
                                history_listG.add(value);
                            }
                        }

                        // Assign the data to the FilterResults
                        filterResults.values = history_listG;
                        filterResults.count = history_listG.size();
                    }
                    return filterResults;
                }

                @Override
                protected void publishResults(CharSequence constraint, FilterResults results)
                {
                    try
                    {
                        if (results != null && results.count > 0)
                        {
                            notifyDataSetChanged();
                        }
                        else
                        {
                            notifyDataSetInvalidated();
                        }
                    }
                    catch (Exception e)
                    {
                        // TODO: handle exception
                    }
                }
            };
            return filter;
        }
    }


}



->Use method saveSearch and clearSearch to save your recent search and for clear the search you saved,(only saved search will be displayed in suggestions next time.)





0 comments:

Post a Comment

Don't lose faith when you see others receive answers to their prayers

An elephant and a dog became pregnant at same time. Three months down the line the dog gave birth to six puppies. Six months later the dog...

 

G-Expo Template by Ipietoon Cute Blog Design