Listview With Searchview Android Studio Example

listview with searchview android

Hello developers, In today’s tutorial, we will learn about listview with searchview android studio example.

In the scenarios where there are many items showed with listview, we need to put search filter functionality.

It let the user find his desired information quickly and easily.

User has to enter search query to find desired item from the listview.

You can develop search functionality using two methods:

  • Using SearchView to enter search query
  • Put Search Query in EditText

In this tutorial we will use SearchView which is in-built UI widget.

If you want to use EditText then read about listview search filter android example.

First, check the output of this tutorial and then go ahead for implementing yourself.

Wait for one minute

If you have not basic idea about listview and adapter, check out listview with image and text tutorial first.

Check listview with button android example for showing button in listview item and manage its click event.

Check listview with checkbox android example for gaining knowledge about how to use the checkbox in listview row.

We will use android’s inbuilt searchview here If you want to use EditText to type a search query,

check out listview search filter android example.

Creating Listview With Searchview Android Example

Step 1: Create a new project in the android studio.

Select Empty activity as a default activity when you are opening a new activity.

Empty activity is useful for adding code snippets with any complexity.

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>

We are just adding one textview in the listview item.

We will process the search query using these texts of every listview row item.

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 getAnimalName() {
        return this.movieName;
    }

}

Above class is the common model structure. We will use the objects of this class to maintain proper listview rows and it’s text values.

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 ) {
        mContext = context;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = new ArrayList<MovieNames>();
        this.arraylist.addAll(MainActivity.movieNamesArrayList);
    }

    public class ViewHolder {
        TextView name;
    }

    @Override
    public int getCount() {
        return MainActivity.movieNamesArrayList.size();
    }

    @Override
    public MovieNames getItem(int position) {
        return MainActivity.movieNamesArrayList.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(MainActivity.movieNamesArrayList.get(position).getAnimalName());
        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        MainActivity.movieNamesArrayList.clear();
        if (charText.length() == 0) {
            MainActivity.movieNamesArrayList.addAll(arraylist);
        } else {
            for (MovieNames wp : arraylist) {
                if (wp.getAnimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
                    MainActivity.movieNamesArrayList.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

}

getView() method will create the each row of the listview.

Following line from getView() method will set the text in the textview.

 holder.name.setText(MainActivity.movieNamesArrayList.get(position).getAnimalName());

Description for filter() method

  • In filter(String charText) method, text present in edittext of searchview which works as a search query, is passed as a parameter.
  • If length charText is 0, means user have not entered search query and the following will be run:
 if (charText.length() == 0) {
            MainActivity.movieNamesArrayList.addAll(arraylist);
        }
  • allAll() method from above code will add the whole arraylist and thus full listview is shown in this case.
  • If a query is entered, then the following will be run:
 for (MovieNames wp : arraylist) {
                if (wp.getAnimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
                    MainActivity.movieNamesArrayList.add(wp);
                }
            }
  • and after that, changes in the adapter are notified by below method
notifyDataSetChanged();

Step 5: Updating activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:iconifiedByDefault="false">

        <requestFocus />
    </SearchView>

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/search" />

</RelativeLayout>

As you can see in the above code, we have put searchview just above the listview.

It will create proper search layout scenario.

Step 6: Updating MainActivity.java class

Put below code in MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {

    // Declare Variables
    private ListView list;
    private ListViewAdapter adapter;
    private SearchView editsearch;
    private String[] moviewList;
    public static ArrayList<MovieNames> movieNamesArrayList = new ArrayList<MovieNames>();

    @Override
    public 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"};

        // Locate the ListView in listview_main.xml
        list = (ListView) findViewById(R.id.listview);

        movieNamesArrayList = 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);
        }

        // Pass results to ListViewAdapter Class
        adapter = new ListViewAdapter(this);

        // Binds the Adapter to the ListView
        list.setAdapter(adapter);

        // Locate the EditText in listview_main.xml
        editsearch = (SearchView) findViewById(R.id.search);
        editsearch.setOnQueryTextListener(this);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, movieNamesArrayList.get(position).getAnimalName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onQueryTextSubmit(String query) {

        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        String text = newText;
        adapter.filter(text);
        return false;
    }
}

Consider the below source code

 for (int i = 0; i < moviewList.length; i++) {
            MovieNames movieNames = new MovieNames(moviewList[i]);
            // Binds all strings into an array
            movieNamesArrayList.add(movieNames);
        }
  • System will execute one for loop.
  • In the every iteration of the for loop, object of the MovieNames class is added in the arraylist.
  • Every object have set the one movie name inside it.

Now focus on this method:

 @Override
    public boolean onQueryTextChange(String newText) {
        String text = newText;
        adapter.filter(text);
        return false;
    }
  • when a user types the query, this method will be executed.
  • For example, if he types “a,” then this method will run, simultaneously for all other words.
  • Now filter(String charText) method will be executed as described earlier.

So it was all about implementing searchview listview android example in android app programmatically. Thank you and keep coding.

Download Source Code

[sociallocker]Download Demo [/sociallocker]