Search and Sort Records in Recycler View in Android. In this article, we will learn how to Search and Sort Records in Recycler View in Android.
Android SDK that we are going to use here is the set of development tools to develop applications for the android platform. With the help of this, we are going to perform Search and Short action in Recycler View with Menu Buttons.
Following will be the project structure:
Step1: Getting Started With Android Studio
- Create a project with Empty Activity.
Implementation library
- Go to res -> Gradle Scripts -> build.gradle
implementation 'androidx.recyclerview:recyclerview:1.2.1'
- RecyclerView is a list view in which we are going to display a list of items and Search and sort them.
- Cards are used to populate RecyclerView.
- ListView is our Adapter Class. Adapters are used to Create and Bind Cards to RecyclerView
- We created an ArrayList of DBHelper class, DBHelper class consist of variable Name and Number, We also created a Backup ArrayList for Sorting.
- findViewById method is used to assign objects to view. for example, we assign recyclerView class object to RecyclerView id in our XML file.
- setLayoutManager
- Add method is used to insert data in the array list, in this we are inserting an object of DBHelper class to our array list which consists of a String and Integer.
- The setAdapter method is used to Assign Adapter to RecyclerView
- onCreateOptionsMenu() is called by the Android runtime when it needs to create the options menu.
- getMenuInflater method is used to inflate Menu with an XML file which is our custom Menu UI
- SearchView is a widget that provides a text view through which we can search through the list
- setOnQueryTextListener method will be triggered when the user clicks on the Search menu
- onQueryTextChange method will change the Filter the list when every user enter text
- Menu item 1 is our sort button. It’s a toggle button
- setOnCheckedChangeListener will listen for a change in toggle button if the user clicks on the button the value of isChecked variable will change
- If the toggle button is checked then the isChecked value will change to true, If it’s true we will add all the elements of the array list to the backup list and sort the original array list with the help of the Comparator class
- Comparator class will short array list according to name
- notifyDataSetChanged method will notify Recycler view for any data change in the list, listView is our adapter
- In else statement, we will clear the original list and add all elements of the backup list to the original list which is not sorted
MainActivity.java
package com.example.searchandshort; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SwitchCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; import androidx.appcompat.widget.SearchView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private ListView listView; private ArrayList<DBHelper> arrayList = new ArrayList<>(); private ArrayList<DBHelper> arrayListBackup = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recycerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); arrayList.add(new DBHelper(12,"Apple")); arrayList.add(new DBHelper(162,"Blackberry")); arrayList.add(new DBHelper(112,"Apricot")); arrayList.add(new DBHelper(132,"Avocado")); arrayList.add(new DBHelper(512,"Banana")); listView = new ListView(arrayList,this); recyclerView.setAdapter(listView); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu,menu); MenuItem menuItem = menu.findItem(R.id.search_bar); SearchView searchView = (SearchView) menuItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { listView.getFilter().filter(newText); return false; } }); MenuItem menuItem1 = menu.findItem(R.id.menu_switch); SwitchCompat switchCompat =(SwitchCompat) menuItem1.getActionView(); switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked==true){ arrayListBackup.addAll(arrayList); Collections.sort(arrayList, new Comparator<DBHelper>() { @Override public int compare(DBHelper o1, DBHelper o2) { return o1.getName().compareTo(o2.getName()); } }); listView.notifyDataSetChanged(); }else { arrayList.clear(); arrayList.addAll(arrayListBackup); arrayListBackup.clear(); listView.notifyDataSetChanged(); } } }); return super.onCreateOptionsMenu(menu); } }
- RelativeLayout is our parent view group used to display children and align them
- Layout_width tag is used to set the width of the layout, match parent will set width to its same as a parent node
- Layout_height tag is used to set the height of layout, wrap content will change the height of view according to data fed into view
- RecyclerView is Recycler list view whenever used scroll down the child which is scrolled up will be recycled
- Layout_centerHorizontal tag will set the view centered on a horizontal plane.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycerView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/search_bar" android:layout_centerHorizontal="true" /> </RelativeLayout>
Step 2:Create Two new Classes ListView and DBHelper
- In this class, we are creating an adapter for our Recycler View
- This Adapter class will be used to populate Recycler view with user data as Card
- Extend adapter class with RecyclerView.Adapter<OuterClass.InnerClass>
- Extend inner class with RecyclerView.ViewHolder class
- Now in the inner class, we use the constructor to assign objects to view
- Override abstract method in ListAdapter class
- onCreateViewHolder method is used to populate Recycler View which we Created in activity_main.xml with list_item.xml
- LayoutInflater is used to inflate Recycler view with Card View
- We pass an array to Recycler view and it gets populated with a card view for every entry of the array
- onBindViewHolder method is used to make changes to card view child nodes
- getItemCount() method will return the size of array
- getFilter method will return filter object which is filtered list for Search
- We are taking a backup Arraylist will all the values of nameList and Searching through the backup list
- Contains method will check for if data passed into the Search box
- We will get the data entered into the search box from the constraint variable
- And changing the nameList Array List by first we clear the list and then add the data that matches from the backup list.
ListView.java
package com.example.searchandshort; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class ListView extends RecyclerView.Adapter<ListView.ListHolder> implements Filterable { private ArrayList<DBHelper> namelist = new ArrayList<>(); private Context context; private ArrayList<DBHelper> backUp; public ListView(ArrayList<DBHelper> namelist,Context context) { this.namelist = namelist; this.context = context; backUp = new ArrayList<>(namelist); } @NonNull @Override public ListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View v =inflater.inflate(R.layout.list_view,parent,false); return new ListHolder(v); } @Override public void onBindViewHolder(@NonNull ListHolder holder, int position) { holder.textView.setText(namelist.get(position).getName()); String s = String.valueOf(namelist.get(position).getNumber()); holder.textView2.setText(s); } @Override public int getItemCount() { return namelist.size(); } @Override public Filter getFilter() { return filter; } Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { ArrayList<DBHelper> s = new ArrayList<>(); if (constraint.toString().isEmpty()){ s.addAll(backUp); }else { for (DBHelper i:backUp){ if (i.getName().toLowerCase().contains(constraint.toString().toLowerCase())){ s.add(i); } } } FilterResults filterResults = new FilterResults(); filterResults.values=s; return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { namelist.clear(); namelist.addAll((ArrayList<DBHelper>)results.values); notifyDataSetChanged(); } }; class ListHolder extends RecyclerView.ViewHolder { private TextView textView; private TextView textView2; public ListHolder(@NonNull View itemView) { super(itemView); textView =(TextView) itemView.findViewById(R.id.TxtListView); textView2 =(TextView) itemView.findViewById(R.id.TxtListView2); } } }
- LinearLayout is our parent node LinearLayout align data or child in Horizontal or vertical orientation
- TextView is a user interface element that displays text to the user
- Margin tag is used to give spacing between views.
List_view.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:showDividers="middle" android:paddingBottom="20dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="10dp"> <TextView android:id="@+id/TxtListView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:layout_marginBottom="5dp" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" /> <TextView android:id="@+id/TxtListView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:layout_marginBottom="5dp" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" /> </LinearLayout> </LinearLayout>
- Here we are using wrapper class to insert data into firebase with the help of the DBHelper constructor
- The DBHelper get method is used to return the String value.
DBHelper.java
public class DBHelper { private int number; private String name; public DBHelper(int number, String name) { this.number = number; this.name = name; } public int getNumber() { return number; } public String getName() { return name; } }
In this way, we learned how to search and sort records in Recycler View in Android.
Android practice tasks
https://codebun.com/login-and-registration-in-android-and-sqlite/
https://codebun.com/login-and-registration-in-android-using-firebase/
https://codebun.com/dynamic-and-static-dropdown-menuspinner-in-android/
https://codebun.com/crud-operation-using-sqlite-in-android/
https://codebun.com/crud-operation-in-android-using-firebase-database/
https://codebun.com/how-to-get-data-from-api-in-android/
https://codebun.com/how-to-create-custom-alert-dialog-in-android/
https://codebun.com/create-a-custom-notification-with-custom-message-in-android/