Android Search to RecyclerView Tutorial

This tutorial explains, how to implement Search functionality in RecyclerView in an Android Application example.

Don't Miss

Also you can get the reference:

Introduction

RecyclerView is the more advanced version of ListView with large data set that can be scrolled.

In this tutorial, we will implement search functionality in RecyclerView. We will use the EditText widget to get the string by user and will search input string in the list to show the filter result. We will use RecyclerView to make the list view

Adding Support Library in the dependencies

To make the list of items, we need to add recyclerview support library in the dependencies. Open build.gradle(app module) and add library in the dependencies. Use the following code to add the library.

dependencies {
   ....
   compile 'com.android.support:recyclerview-v7:23.1.1'
   ....
}

Creating layout

We have to add RecyclerView to display the list of items and a EditText to input the string or keyword we need to search in the list. So, we will add the RecyclerView and EditText in the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="app.searchinrecyclerview.MainActivity">

<EditText
android:id="@+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textSize="16sp"
android:hint="Search here"
android:layout_marginTop="20dp" />

<View
android:id="@+id/border"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_below="@+id/search"
android:layout_marginTop="14dp"
android:background="#d3d3d3"/>

<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:layout_marginTop="10dp"
android:layout_below="@+id/border"/>

</RelativeLayout>

Create a new list_item.xml to show the list of items. Add the following code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.numetriclabz.androidsearch.MainActivity">

  <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

   <TextView
      android:id="@+id/country_name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:textColor="#0b0080"
      android:textSize="16dp" />

 </RelativeLayout>

</RelativeLayout>

Initialize the Id of EditText and RecyclerView

To use the properties of EditText and RecyclerView, we initialize the id of EditText and RecyclerView.

public class MainActivity extends AppCompatActivity {
   private RecyclerView mRecyclerView;
   public EditText search;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     search = (EditText) findViewById( R.id.search);
     mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
  }
}

To improve the performance of RecyclerView, add the following code:

public class MainActivity extends AppCompatActivity {
   private RecyclerView mRecyclerView;
   public EditText search;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     search = (EditText) findViewById( R.id.search);
     mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
     mRecyclerView.setHasFixedSize(true);
   }
}

Set the Layout Manager

Add the LayoutManager to manage the position of its items in the RecyclerView

public class MainActivity extends AppCompatActivity {
   private RecyclerView mRecyclerView;
   public EditText search;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     search = (EditText) findViewById( R.id.search);
     mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
     mRecyclerView.setHasFixedSize(true);
     mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
   }
}

Creating an ArrayList

Create an ArrayList to populate the data in the list. We will create a countryList() method. In this method, we will add the list of item in the array list.

public class MainActivity extends AppCompatActivity {
   private RecyclerView mRecyclerView;
   public EditText search;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     search = (EditText) findViewById( R.id.search);
     mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
     mRecyclerView.setHasFixedSize(true);
     mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
     countryList();  // in this method, Create a list of items.
   }

   // this method is used to create list of items.
  public void countryList(){
     list.add("Afghanistan");
     list.add("Albania");
    list.add("Algeria");
    list.add("Bangladesh");
    list.add("Belarus");
    list.add("Canada");
    list.add("Cape Verde");
    list.add("Central African Republic");
    list.add("Denmark");
    list.add("Dominican Republic");
    list.add("Egypt");
    list.add("France");
    list.add("Germany");
    list.add("Hong Kong");
    list.add("India");
    list.add("Iceland");
  }
}

Creating an Adapter class

The RecyclerView.Adapter class is similar to Adapter class of listview and this class has a special feature to add custom ViewHolder class to improve performance of RecyclerView class. To Learn how to implement Adapter class go to Android RecyclerView with animation tutorial. Final Adapter class is given below:

public class SimpleAdapter extends
    RecyclerView.Adapter<SimpleAdapter.MyViewHolder> {

    private List<String> list_item ;
    public Context mcontext;

    public SimpleAdapter(List<String> list, Context context) {

        list_item = list;
        mcontext = context;
    }

    // Called when RecyclerView needs a new RecyclerView.ViewHolder of the given type to represent an item.
    @Override
    public SimpleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
      int viewType) {
      // create a layout
     View view = LayoutInflater.from(parent.getContext()).inflate(
     R.layout.list_item, null);

     MyViewHolder myViewHolder = new MyViewHolder(view);
     return myViewHolder;
    }

    // Called by RecyclerView to display the data at the specified position.
    @Override
    public void onBindViewHolder(final MyViewHolder viewHolder, final int position ) {

    viewHolder.country_name.setText(list_item.get(position));

    viewHolder.country_name.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

Toast.makeText(mcontext, list_item.get(position),
Toast.LENGTH_LONG).show();
}
});

}

// initializes textview in this class
public static class MyViewHolder extends RecyclerView.ViewHolder {

public TextView country_name;

public MyViewHolder(View itemLayoutView) {
super(itemLayoutView);

country_name = (TextView) itemLayoutView.findViewById(R.id.country_name);

}
}

//Returns the total number of items in the data set hold by the adapter.
@Override
public int getItemCount() {
return list_item.size();
}

}

Set the Adapter

Set the adapter by using setAdapter() method in the MainActivity.java file.

public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
public EditText search;
private List<String> list = new ArrayList<String>();
public SimpleAdapter mAdapter;

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

search = (EditText) findViewById( R.id.search);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
countryList();  // in this method, Create a list of items.

// call the adapter with argument list of items and context.
mAdapter = new SimpleAdapter(list,this);
mRecyclerView.setAdapter(mAdapter);

}

// this method is used to create list of items.
public void countryList(){

list.add("Afghanistan");
list.add("Albania");
list.add("Algeria");
list.add("Bangladesh");
list.add("Belarus");
list.add("Canada");
list.add("Cape Verde");
list.add("Central African Republic");
list.add("Denmark");
list.add("Dominican Republic");
list.add("Egypt");
list.add("France");
list.add("Germany");
list.add("Hong Kong");
list.add("India");
list.add("Iceland");
}
}

Adding Search Functionality

We will create addTextListener() method to set the EditText Listener method. This Listener method will search in the list for a matching string, which is provided by user. Call the notifyDataSetChanged() method to change the data set in the RecyclerView.

public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
public EditText search;
private List<String> list = new ArrayList<String>();
public SimpleAdapter mAdapter;

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

search = (EditText) findViewById( R.id.search);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
countryList();  // in this method, Create a list of items.

// call the adapter with argument list of items and context.
mAdapter = new SimpleAdapter(list,this);
mRecyclerView.setAdapter(mAdapter);

addTextListener();
}

// this method is used to create list of items.
public void countryList(){

list.add("Afghanistan");
list.add("Albania");
list.add("Algeria");
list.add("Bangladesh");
list.add("Belarus");
list.add("Canada");
list.add("Cape Verde");
list.add("Central African Republic");
list.add("Denmark");
list.add("Dominican Republic");
list.add("Egypt");
list.add("France");
list.add("Germany");
list.add("Hong Kong");
list.add("India");
list.add("Iceland");
}

public void addTextListener(){

search.addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable s) {}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

public void onTextChanged(CharSequence query, int start, int before, int count) {

query = query.toString().toLowerCase();

final List<String> filteredList = new ArrayList<>();

for (int i = 0; i < list.size(); i++) {

final String text = list.get(i).toLowerCase();
if (text.contains(query)) {

filteredList.add(list.get(i));
}
}

mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mAdapter = new SimpleAdapter(filteredList, MainActivity.this);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();  // data set changed
}
});
}
}

search in recyclerviewsearch to recyclerview

22 COMMENTS

  1. hey abhay , can you make one tutorial where each row of the recyler view has a textview and a button , on clicking of this button i will increaset the value of the text view , i am doing this But after scrolling the value of thext view again setting to the 1 default value

    pls make this bro

  2. Thank you Sir..for this tutorials…..but sir in my Project your above code is worked….but i have one more Action in RecycleView……when i search in EditText it properly worked….but after Searching when i click on any Country click event not worked…why sir…?

  3. Good tutorial !!! Thanks !!!
    But don’t you think filteredList is going to be set to a new instance of an adapter on every text change of edit text?
    We can expose a method in adapter and replace the current list with new filtered list followed by notifyDataSetChanged()

    public void setCountries(ArrayList newCountries) {
    countries = newCountries;
    notifyDataSetChanged();
    }

    Thanks

  4. Very Helpful Tutorial!! This tutorial searches in one RecyclerView in the same Activity using EditText..
    Can you please suggest how to use the EditText or SearchView to search for items in different Activities..
    I have seven RecyclerViews, in seven separate Activities.. I want to filter the results for items in all the RecyclerViews of my Activities..

    What changes i have to make to the CustomAdapter class or to the filter() method, and also to the MainActivity class as suggested by you in this tutorial..

    Hope you understood my problem… If you could mail me the suggestion .. it would be of great help to me…
    my mail id is ab5593@gmail.com ..

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com