Search code examples
androidsearchviewandroid-recyclerviewandroid-filterable

filter Recycler view using searchview


I try to Filter RecyclerView by placing a SearchView on Toolbar, i followed this tutorial from its 25 minutes since it express exactly what am looking for, upon implementation from tutorial they used "ArrayList newList= new ArrayList<>() "which work fine but i want to implement it using this form "ArrayList > newList= new ArrayList<>()" since is the format i have been through out the project .I tried to do it as follows:

/// Activity

public class MainActivity extends AppCompatActivity implements    SearchView.OnQueryTextListener {
// DB Class to perform DB related operations
DBController controller = new DBController(MainActivity.this);
// Progress Dialog Object
ArrayList<HashMap<String, String>> arrayList= new ArrayList<HashMap<String, String>> ();
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private UsersAdapter adapter;
@Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);
 // Get User records from SQLite DB
    ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
    // If users exists in SQLite DB
    if (userList.size() != 0) {
        recyclerView = (RecyclerView) findViewById(R.id.usersList);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        controller = new DBController(MainActivity.this);
        ArrayList<HashMap<String, String>> users = controller.getAllUsers();
        adapter = new UsersAdapter(users,this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
     }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    final MenuItem searchItem = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
  searchView.setOnQueryTextListener(this);
    return true;

}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here.
    int id = item.getItemId();
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

    @Override
      public boolean onQueryTextChange(String newText) {
    newText = newText.toLowerCase();
    ArrayList<HashMap<String, String>> newList= new ArrayList<>();
    for(  HashMap<String, String> entry : arrayList){
        String name= entry.put("userName",newText);
        if(name.contains(newText)){
      newList.add(entry);
    }}
    adapter.setFilter(newList);
     return  true;
    }
     }

///Adapter class

    public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserViewHolder> {
ArrayList<HashMap<String, String>> mDataSet= new ArrayList<HashMap<String, String>> ();
        Context ctx;
       public UsersAdapter(ArrayList<HashMap<String, String>> mDataSet,Context ctx)      {
       this.mDataSet = mDataSet;
       this.ctx=ctx;
        }
      @Override
      public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View v =    LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row, parent,       false);
      UserViewHolder userViewHolder = new UserViewHolder(v,mDataSet,ctx);
       return userViewHolder;
         }
        @Override
     public void onBindViewHolder(UserViewHolder holder, int position) {
    holder.name_entry.setText(mDataSet.get(position).get("userId"));
    holder.email_entry.setText(mDataSet.get(position).get("userName"));
    holder.icon_entry.setText(""+mDataSet.get(position).get("number"));
          }
         @Override
        public int getItemCount() {
              return mDataSet.size();
           }

     public static class UserViewHolder extends RecyclerView.ViewHolder  {
    CardView cardView;
    TextView name_entry, email_entry, icon_entry;
    Context ctx;
        ArrayList<HashMap<String, String>> mDataSet= new   ArrayList<HashMap<String, String>> ();
        public UserViewHolder(View itemView, ArrayList<HashMap<String,  String>>        mDataSet,Context ctx) {
            super(itemView);
            this.mDataSet=mDataSet;
         this.ctx= ctx;
         cardView = (CardView) itemView.findViewById(R.id.user_layout);
         name_entry = (TextView) itemView.findViewById(R.id.name_entry);
         email_entry = (TextView) itemView.findViewById(R.id.email_entry);
         icon_entry = (TextView) itemView.findViewById(R.id.icon_entry);
              }
               }

        @Override
       public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
           }

       public void setFilter(ArrayList<HashMap<String, String>> newList){
        //we have used hashmap,  find how to use it here
    mDataSet= new ArrayList<HashMap<String, String>>();
    mDataSet.addAll(newList);
    notifyDataSetChanged();
        }

      }

but when i click the search icon the recycler view disappear with all data until i resume the app. On my point of view i thing am adding empty data though am not sure since am kind new to android , Any idea on where did i get it wrong and how can i make it work. l know there is this solution but i did not get it well.


Solution

  • You have declared in your Activity class:

    ArrayList<HashMap<String, String>> arrayList= new ArrayList<HashMap<String, String>> ();
    

    but you didn't assign it. It should be

     arrayList = controller.getAllUsers();
    

    Because you have filter by this field and there is always data there. And it's better to rename this variable from arrayList to userList :)