Skip to content
Related Articles

Related Articles

SearchView in Android with RecyclerView
  • Last Updated : 28 Jan, 2021

Many apps represent data in the form of huge lists and for filtering these lists we have seen the SearchView present inside these apps. So for filtering this list of data we generally use a SearchView. In this article, we will take a look at the implementation of Search View in Android with a RecyclerView in Android. 

What we are going to build in this article? 

We will be building a simple application in which we will display a list of data in the RecyclerView. We will be displaying the list of courses with its description and on that recycler view, we will add a SearchView which will be used to filter the data in our Recycler View. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file



Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--recycler view to display our data-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
  
</RelativeLayout>

Step 3: Creating a modal class for storing our data

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as CourseModal and add the below code to it. 

Java




public class CourseModal {
  
    // variables for our course
    // name and description.
    private String courseName;
    private String courseDescription;
  
    // creating constructor for our variables.
    public CourseModal(String courseName, String courseDescription) {
        this.courseName = courseName;
        this.courseDescription = courseDescription;
    }
  
    // creating getter and setter methods.
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseDescription() {
        return courseDescription;
    }
  
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
}

Step 4: Creating a layout file for our item of RecyclerView

Navigate to the app > res > layout > Right-click on it > New > layout resource file and name your layout as course_rv_item and add the below code to it. 

XML






<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
  
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  
        <!--text view for our course name-->
        <TextView
            android:id="@+id/idTVCourseName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="Course Name"
            android:textColor="@color/black"
            android:textSize="18sp" />
  
        <!--text view for our course description-->
        <TextView
            android:id="@+id/idTVCourseDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVCourseName"
            android:padding="5dp"
            android:text="COurse Description"
            android:textColor="@color/black" />
  
    </RelativeLayout>
      
</androidx.cardview.widget.CardView>

Step 5: Creating an adapter class for setting data to items of our RecyclerView 

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseAdapter and add the below code to it. 

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.ViewHolder> {
     
    // creating a variable for array list and context.
    private ArrayList<CourseModal> courseModalArrayList;
    private Context context;
  
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    // method for filtering our recyclerview items.
    public void filterList(ArrayList<CourseModal> filterllist) {
        // below line is to add our filtered
        // list in our course array list.
        courseModalArrayList = filterllist;
        // below line is to notify our adapter 
        // as change in recycler view data.
        notifyDataSetChanged();
    }
  
    @NonNull
    @Override
    public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseDescTV.setText(modal.getCourseDescription());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
          
        // creating variables for our views.
        private TextView courseNameTV, courseDescTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}

Step 6: Creating a menu file for our SearchView

Navigate to the app > res > Right-click on it > New > Directory and give a name to your directory as the menu. After creating a new directory we have to create a new menu file inside it. For creating a new menu file. Navigate to the app > res > menu > Right-click on it > New > menu resource file, name it as search_menu and add the below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
<menu 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
      
    <!--item for our search view with its id-->
    <item
        android:id="@+id/actionSearch"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />
      
</menu>

Step 7: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for
    // our ui components.
    private RecyclerView courseRV;
      
    // variable for our adapter
    // class and array list
    private CourseAdapter adapter;
    private ArrayList<CourseModal> courseModalArrayList;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
          
        // calling method to 
        // build recycler view.
        buildRecyclerView();
    }
  
    // calling on create option menu
    // layout to inflate our menu file.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // below line is to get our inflater
        MenuInflater inflater = getMenuInflater();
          
        // inside inflater we are inflating our menu file.
        inflater.inflate(R.menu.search_menu, menu);
          
        // below line is to get our menu item.
        MenuItem searchItem = menu.findItem(R.id.actionSearch);
          
        // getting search view of our item.
        SearchView searchView = (SearchView) searchItem.getActionView();
         
        // below line is to call set on query text listener method.
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
  
            @Override
            public boolean onQueryTextChange(String newText) {
                // inside on query text change method we are 
                // calling a method to filter our recycler view.
                filter(newText);
                return false;
            }
        });
        return true;
    }
  
    private void filter(String text) {
        // creating a new array list to filter our data.
        ArrayList<CourseModal> filteredlist = new ArrayList<>();
          
        // running a for loop to compare elements.
        for (CourseModal item : courseModalArrayList) {
            // checking if the entered string matched with any item of our recycler view.
            if (item.getCourseName().toLowerCase().contains(text.toLowerCase())) {
                // if the item is matched we are
                // adding it to our filtered list.
                filteredlist.add(item);
            }
        }
        if (filteredlist.isEmpty()) {
            // if no item is added in filtered list we are 
            // displaying a toast message as no data found.
            Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();
        } else {
            // at last we are passing that filtered
            // list to our adapter class.
            adapter.filterList(filteredlist);
        }
    }
  
    private void buildRecyclerView() {
          
        // below line we are creating a new array list
        courseModalArrayList = new ArrayList<>();
          
        // below line is to add data to our array list.
        courseModalArrayList.add(new CourseModal("DSA", "DSA Self Paced Course"));
        courseModalArrayList.add(new CourseModal("JAVA", "JAVA Self Paced Course"));
        courseModalArrayList.add(new CourseModal("C++", "C++ Self Paced Course"));
        courseModalArrayList.add(new CourseModal("Python", "Python Self Paced Course"));
        courseModalArrayList.add(new CourseModal("Fork CPP", "Fork CPP Self Paced Course"));
          
        // initializing our adapter class.
        adapter = new CourseAdapter(courseModalArrayList, MainActivity.this);
          
        // adding layout manager to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
          
        // setting layout manager 
        // to our recycler view.
        courseRV.setLayoutManager(manager);
          
        // setting adapter to 
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}

Now run your app and see the output of the app. 

Output:

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :