N
N
Neonoviiwolf2017-07-23 03:02:50
Java
Neonoviiwolf, 2017-07-23 03:02:50

I overwrite ArrayList into ArrayAdapter, how to do it right?

Good, I wrote my own adapter for AppCompatAutoCompleteTextView, the search works, but I overwrite the data in the ArrayList when searching, and if I delete the text from the field, the search result remains the same, how to do a search by input? here is the code

package www.finefood.ExpansionEditText;


import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

import java.util.ArrayList;

import www.finefood.R;

public class MyArrayAdapter extends ArrayAdapter<MyForArrayAdapter> {

    private ArrayList<MyForArrayAdapter> list = new ArrayList<>();
    private Activity context;
    private Integer resource;
    private LayoutInflater inflater;

    public MyArrayAdapter(Context context, int resource,
                          ArrayList<MyForArrayAdapter> list1) {
        super(context, resource, list1);
        this.resource = resource;
        this.context = (Activity) context;
        this.list = list1;
        inflater = this.context.getLayoutInflater();
    }

    private MyFilter filter;

    @Override
    public Filter getFilter() {
        if (filter == null)
            filter = new MyFilter();
        return filter;
    }

    static class ViewHolder {
        protected TextView text;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        String str = list.get(position).getNameProduct();
        ViewHolder viewHolder;
        if (convertView == null) {
            view = inflater.inflate(resource, null);
            viewHolder = new ViewHolder();
            viewHolder.text = (TextView) view.findViewById(R.id.text_view_array_adapter);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        if (viewHolder != null)
            viewHolder.text.setText(str);
        return view;
    }

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

    @Override
    public MyForArrayAdapter getItem(int position) {
        return list.get(position);
    }

    private class MyFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            charSequence = charSequence.toString().toLowerCase();
            FilterResults results = new FilterResults();
            if (charSequence.toString().length() > 0) {
                ArrayList<MyForArrayAdapter> tempList = new ArrayList<>();
                for (int i = 0; list.size() > i; ++i) {
                    MyForArrayAdapter myArrayAdapter = list.get(i);
                    if (myArrayAdapter.getNameProduct().toLowerCase().contains(charSequence))
                        tempList.add(myArrayAdapter);
                }
                results.count = tempList.size();
                results.values = tempList;
            } else {
                synchronized (this) {
                    results.count = list.size();
                    results.values = list;
                }
            }
            return results;
        }
//этот код содрал с какого-то сайта, но там использовался  ArrayAdapter<String>
        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            if (filterResults.values != null) {
                list = (ArrayList<MyForArrayAdapter>) filterResults.values;
                notifyDataSetChanged();
//проблема тут, тут очищается ArrayList, тем самым 
//затирается, если не очищать, то начинает заполняться 
//разрастаться после каждого введённого символа
                clear(); 
//
                    for (int i = 0; list.size() > i; i++)
                        add(list.get(i));
                notifyDataSetInvalidated();
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
subway, 2017-07-23
@Neonoviiwolf

It is possible to create 2 arrayList in which there will be filtered elements and a copy of all elements. As soon as the user erases his request, we fill the array from the array with a copy. Example:

public class ItemAdapter extends RecyclerView.Adapter<ItemViewHolder> {
  private List<Item> mItemList = new ArrayList<>();
  private List<Item> mItemsCopy = new ArrayList<>();

   /**
   * Фильтрует отображаемые пользователю данные при вводе текста в поиск
   *
   * @param query the query
   */
  void filter(String query) {
    mItemList.clear();
    if (query.isEmpty()) {
      mItemList.addAll(mItemsCopy);
    } else {
      query = query.toLowerCase();
      for (Item item : mItemsCopy) {
          if (item.getUserName().toLowerCase().contains(query)) {
            mItemList.add(item);
          }
      }
    }
    notifyDataSetChanged();
  }

We hang a text watcher on the EditText and call the filter method of the adapter in onTextChanged and pass what the user entered.
The whole source of my adapter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question