Home > Enterprise >  RecyclerView list search (filter) EditText problem
RecyclerView list search (filter) EditText problem

Time:10-17

I wanted to add a search function to my recyclerview list, I tried the code on the internet by looking at the textbook, it worked fine but if you delete the letters in edittext the list doesn't go back, it just deletes the list .

Example: If I type '' I 12345 '' in edittext, the rest will be deleted and only '' I 12345 '' will remain, but if I delete the text in edittext, the list will not return.

please help for fix!

here my all codes:

MainActivity java:

public class MainActivity extends AppCompatActivity {

    RecyclerViewAdapter recyclerViewAdapter;

    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerview1);

        //here start search code


        EditText editText = findViewById(R.id.izlash_edittext);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                filter(s.toString());
            }
        });


        //here end search code

        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        ArrayList<Item> items = new ArrayList<>();

        items.add(new Item("start", R.drawable.start));
        items.add(new Item("end", R.drawable.end));

        recyclerView.setAdapter(recyclerViewAdapter);

    }

        //here start search code
    private void filter(String title) {
        ArrayList<Item> filteredList = new ArrayList<>();

        for (Item item : recyclerViewAdapter.items) {
            if (item.title.toLowerCase().contains(title.toLowerCase())) {
                filteredList.add(item);
            }

            recyclerViewAdapter.filterList(filteredList);
        }
    }

        //here end search code

}

RecyclerViewAdapter java:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    ArrayList<Item> items;
    ItemClickListener itemClickListener;

    public RecyclerViewAdapter(ArrayList<Item> items, ItemClickListener itemClickListener) {
        this.items = items;
        this.itemClickListener = itemClickListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {

        Item item = items.get(position);

        holder.title.setText(item.title);
        holder.imageView.setImageResource(item.image);

        holder.itemView.setOnClickListener(view -> {
            itemClickListener.onClick(item);
        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    //here start search code

    public void filterList(ArrayList<Item> filteredList) {
        items = filteredList;
        notifyDataSetChanged();
    }

    //here end search code

    public interface ItemClickListener {
        void onClick(Item item);
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView title;
        ImageView imageView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            title = itemView.findViewById(R.id.textView1);
            imageView = itemView.findViewById(R.id.imageview1);
        }

    }
}

Item java:

public class Item {

    String title;
    int image;
    String qisqaMalumot;
    String uzunMalumot;

    public Item(String title, int image, String qisqaMalumot, String uzunMalumot) {
        this.title = title;
        this.image = image;
        this.qisqaMalumot = qisqaMalumot;
        this.uzunMalumot = uzunMalumot;
    }
}

please help me.

CodePudding user response:

 for (Item item : recyclerViewAdapter.items) {
        if (item.title.toLowerCase().contains(title.toLowerCase())) {
            filteredList.add(item);
        }

when you search in recyclerViewAdapter.items the recyclerview replaced with new data and old data gone .

first make global list ArrayList<Item> items = new ArrayList<>();

public class MainActivity extends AppCompatActivity {

RecyclerViewAdapter recyclerViewAdapter;
ArrayList<Item> items = new ArrayList<>();
RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  } 

second replace items in your for Loop:

  for (Item item : items) {
        if (item.title.toLowerCase().contains(title.toLowerCase())) {
            filteredList.add(item);
        }

its done !

CodePudding user response:

First you need to implement the Filterable in your adapter.then you need to keep a filtered item in the listadapter so that you can revert back to its old state. When you login to query from edittext in main activity, this way the adapter can change and revert back to its old state. If you edit the code according to yourself, it will work smoothly.

      public class BulletinAdapter extends RecyclerView.Adapter<BulletinAdapter.BulletinVHolder> implements Filterable {

    private Context context;
    private List<EventResponseItem> eventsItemList;
    private List<EventResponseItem> filteredList;

    public BulletinAdapter(Context context, List<EventResponseItem> eaItemList) {
        this.context = context;
        this.filteredList = eaItemList;
    }

    @NonNull
    @Override
    public BulletinVHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new BulletinVHolder(RowNewaddBinding.inflate(LayoutInflater.from(context), parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull BulletinVHolder holder, int position) {
        EventResponseItem eaItem = filteredList.get(position);

        if (eaItem != null) {
            holder.bind.rowNewMatchId.setText(String.valueOf(eaItem.getEid()));
        }

    }

    @Override
    public int getItemCount() {
        if (filteredList != null && filteredList.size() > 0) {
            return filteredList.size();
        } else {
            return 0;
        }
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                String charString = constraint.toString();
                if (constraint.length() == 0) {
                    filteredList = eventsItemList;
                } else {
                    List<EventResponseItem> filterList = new ArrayList<>();
                    for (EventResponseItem modelMovie : eventsItemList) {
                        if (modelMovie.getEprt().get(0).getPn().toLowerCase().contains(charString) | modelMovie.getEprt().get(1).getPn().toLowerCase().contains(charString)) {
                            filterList.add(modelMovie);
                        }
                    }
                    filteredList = filterList;
                }
                FilterResults filterResults = new FilterResults();
                filterResults.values = filteredList;
                return filterResults;

            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                filteredList = (List<EventResponseItem>) results.values;
                notifyDataSetChanged();
            }
        };
    }

    class BulletinVHolder extends RecyclerView.ViewHolder {

        private RowNewaddBinding bind;

        public BulletinVHolder(@NonNull RowNewaddBinding bind) {
            super(bind.getRoot());
            this.bind = bind;
        }
    }
}

MainActivity.class..

private List<EventResponseItem> eventsItemList; //set list data
        private BulletinAdapter bulletinAdapter; //recyclerview set adapter...(data and layoutmanager)
       bulletinAdapter = new BulletinAdapter(MatchAddNew.this,eventsItemList);
                        bind.matchAddNewRecyclerView.setLayoutManager(new LinearLayoutManager(MatchAddNew.this));
                        bind.matchAddNewRecyclerView.setAdapter(bulletinAdapter); 
            search(bind.searchViewNewMatch); //viewBinding your edittext...
            
            private void search(SearchView searchView) {
                    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                        @Override
                        public boolean onQueryTextSubmit(String s) {
                            return false;
                        }
            
                        @Override
                        public boolean onQueryTextChange(String s) {
                            if (bulletinAdapter != null) {
                                bulletinAdapter.getFilter().filter(s.toLowerCase());
                            }
            
                            return true;
                        }
                    });

            }
  • Related