Hello, all learners. This is a listview search filter android studio example.
We are going to implement a search filter feature in the listview in this demo.
Search functionality reduces navigation complexity for the user and also saves user’s valuable time.
Commonly, you can implement search filter functionality using two methods.
First is using EditText and Second is using Search View
When there are too many items in the listview, the user needs a filter so that he can find an item by filtering by name, occupation, address, etc.
Search filter provides high user interface value which increases user’s overall satisfaction while using your app.
1. Android ListView Search Filter With EditText
In this tutorial example, I am going to use EditText method.
It means that I will provide EditText to the user to enter the search query.
First, check the output of this tutorial in below video.
Step 1: Create a new project in Android Studio.
When you are creating a new project in android studio, I recommend you to choose “Empty activity” as a default activity.
Empty activity gives fresh work space without any pre-written code.
Step 2: Creating row layout file for listview
Create one layout resource file and name it as listview_item.xml and copy below code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp"> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
Above layout file represents the layout structure for each row of listview.
We will just add only one textview in every row of the listview.
Step 3: Creating MovieNames.java class (It is Model class)
Create a new class named MovieNames.java and add following
public class MovieNames { private String movieName; public MovieNames(String movieName) { this.movieName = movieName; } public String getMovieName() { return this.movieName; } }
Step 4: Creating ListViewAdapter.java class:
Create new java class named ListViewAdapter and add following code
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.Locale; public class ListViewAdapter extends BaseAdapter { // Declare Variables Context mContext; LayoutInflater inflater; private ArrayList<MovieNames> arraylist; public ListViewAdapter(Context context, ArrayList<MovieNames> arraylist) { mContext = context; inflater = LayoutInflater.from(mContext); this.arraylist = arraylist; } public class ViewHolder { TextView name; } @Override public int getCount() { return arraylist.size(); } @Override public MovieNames getItem(int position) { return arraylist.get(position); } @Override public long getItemId(int position) { return position; } public View getView(final int position, View view, ViewGroup parent) { final ViewHolder holder; if (view == null) { holder = new ViewHolder(); view = inflater.inflate(R.layout.listview_item, null); // Locate the TextViews in listview_item.xml holder.name = (TextView) view.findViewById(R.id.name); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } // Set the results into TextViews holder.name.setText(arraylist.get(position).getMovieName()); return view; } }
Step 5: Updating activity_main.xml file
Add below code in activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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.example.parsaniahardik.searchedit.MainActivity" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:hint="enter query" android:singleLine="true"> <requestFocus/> </EditText> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listView" android:divider="#694fea" android:dividerHeight="1dp" /> </LinearLayout>
Step 6: Updating MainActivity.java class
Put below code in MainActivity.java
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.SearchView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private EditText etsearch; private ListView list; private ListViewAdapter adapter; private String[] moviewList; public static ArrayList<MovieNames> movieNamesArrayList; public static ArrayList<MovieNames> array_sort; int textlength = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Generate sample data moviewList = new String[]{"Xmen", "Titanic", "Captain America", "Iron man", "Rocky", "Transporter", "Lord of the rings", "The jungle book", "Tarzan","Cars","Shreck"}; list = (ListView) findViewById(R.id.listView); movieNamesArrayList = new ArrayList<>(); array_sort = new ArrayList<>(); for (int i = 0; i < moviewList.length; i++) { MovieNames movieNames = new MovieNames(moviewList[i]); // Binds all strings into an array movieNamesArrayList.add(movieNames); array_sort.add(movieNames); } adapter = new ListViewAdapter(this,movieNamesArrayList); list.setAdapter(adapter); etsearch = (EditText) findViewById(R.id.editText); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, array_sort.get(position).getMovieName(), Toast.LENGTH_SHORT).show(); } }); etsearch.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { textlength = etsearch.getText().length(); array_sort.clear(); for (int i = 0; i < movieNamesArrayList.size(); i++) { if (textlength <= movieNamesArrayList.get(i).getMovieName().length()) { Log.d("ertyyy",movieNamesArrayList.get(i).getMovieName().toLowerCase().trim()); if (movieNamesArrayList.get(i).getMovieName().toLowerCase().trim().contains( etsearch.getText().toString().toLowerCase().trim())) { array_sort.add(movieNamesArrayList.get(i)); } } } adapter = new ListViewAdapter(MainActivity.this, array_sort); list.setAdapter(adapter); } }); } }
Explanation of Above code
Look at the below code
moviewList = new String[]{"Xmen", "Titanic", "Captain America", "Iron man", "Rocky", "Transporter", "Lord of the rings", "The jungle book", "Tarzan","Cars","Shreck"};
moviewList is a string array. This string array contains the names of the movies.
We will use this string array in the below for loop
for (int i = 0; i < moviewList.length; i++) { MovieNames movieNames = new MovieNames(moviewList[i]); // Binds all strings into an array movieNamesArrayList.add(movieNames); array_sort.add(movieNames); }
Above for loop creates the object of the MovieNames class in it’s every iteration.
After creating an object, we will add it in the movieNamesArrayList.
Description of filter logic
Focus on the following code
public void onTextChanged(CharSequence s, int start, int before, int count) { textlength = etsearch.getText().length(); array_sort.clear(); for (int i = 0; i < movieNamesArrayList.size(); i++) { if (textlength <= movieNamesArrayList.get(i).getMovieName().length()) { Log.d("ertyyy",movieNamesArrayList.get(i).getMovieName().toLowerCase().trim()); if (movieNamesArrayList.get(i).getMovieName().toLowerCase().trim().contains( etsearch.getText().toString().toLowerCase().trim())) { array_sort.add(movieNamesArrayList.get(i)); } } } adapter = new ListViewAdapter(MainActivity.this, array_sort); list.setAdapter(adapter);
textlength contains a total number of characters of a search query.
if movie name contains set of characters same as a search query, then it will be inserted in array_sort.
array_sort will have sorted values and will be put in the adapter.
So that is all for listview search filter android example. Keep visiting us for more exciting tutorials. Thanks š