Android Action Bar SearchView Tutorial with Android Search Bar Example

SearchView Introduction

SearchView is a User Interface widget that provides search features for any query. It shows the suggestions as a query result and allows the user to pick from the suggestions. In Action Bar, SearchView can collapse as a menu item. The preferred way to provide search is in Action Bar of the Android application.
In this tutorial, you will learn how to create and use SearchView in Android application. This tutorial will also explain the concept of SearchView in Action Bar use of Android Search bar example for ListView.

Android Search Bar Example with ListView

First of all, implement a ListView and populate it with the help of an Adapter for Android Search Bar Example.

Create ListView

Open the layout file of the activity, where you want to implement the ListView. Create a ListView either by drag and drop or through the code.

ListView in Android
ListView in Android

Populate ListView

You can populate the ListView with the help of Adapter as well as you can use RecyclerView. If you want to load data from some online source that provides JSON, then use Retrofit library with Gson to get JSON data in your application. This Android Search Bar example uses simple Adapter with fixed array to populate the ListView for better understanding.

Create a string array and use ArrayAdapter to populate the ListView. Also, add the click listener for ListView item click.

Click here for More details about ArrayAdapter and ListView.

Until now, Android Search Bar Example just have a ListView which is populated with the help of ArrayAdapter.

Components of Search Bar

Moving further, create a new Search widget. Before implementing the Android Search Bar example widget. You must know about the components of the Search bar.

A search bar is comprised of a menu item which acts as Action bar search widget to display the search field. i.e. to show the Search Bar.  And a searchable layout file. It defines the behavior of the SearchView. This searchable layout file contains the hint (What Search is for).

Search menu resource

The very first step to Search bar is to create a menu resource file. So first create a new menu folder in the resource(res) directory and add a new menu file. This menu file contains the search widget and its properties i.e. the title of the SearchView, Id, and other properties.

Searchable Configuration

To describe the behavior of the Search Bar, create a searchable configuration. So create a new xml folder in the resource(res) directory and add a new layout file.

Now the directory structure will look like:

Directory structure of Android Search Bar Example
Directory structure for Android Search Bar Example

Other Configurations

Add Search Filter inside <intent-filter> tags.

Modify the <activity android:name=”.MainActivity”> as

Now, to configure searchable.xml file add meta description inside <activity ></activity> tags.

 

Inflate Action Bar

In onCreateOptionsMenu(Menu menu) overridden method, inflate the Action Bar.

Use SearchManager to consume Search_Service.

Instantiate SearchView and set searchable info for the SearchView from SearchManager. Also set onQeuryTextListener() to listen to the search queries.

Android Search Bar example with ListView
Android Search Bar example with ListView

Complete Code for MainActivity.java

Download SearchView in Action Bar for ListView Example

Hope that you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!

  • Muhammad Salma Nabila Alibasyi

    nice tutorial, I have an error in mainactivity for cannot resolve method getFilter() and cannot resolve method getItemAtPosition

    any solution?

    • Beginners Heap Free Tutorials

      Thankyou! ArrayAdapter has built-in getFilter() method. If you are not using ArrayAdapter you must implement Filterable. Compare your code with the attached source files to track the error.

      Best Regards,
      Beginners Heap

      • Muhammad Salma Nabila Alibasyi

        that’s not work for me
        I have tried to use recyclerview with retrofit and implement your code, but there is still error with cannot resolve method getFilter() and cannot resolve method getItemAtPosition.

        • Beginners Heap Free Tutorials

          You can use recyclerView.getAdapter().getList().get(position) instead of getItemAtPosition(). There is also a RecyclerView example -> https://www.beginnersheap.com/card-view-recycler-view-example-tutorial/ in which a Toast is displayed on item click.
          In the case of RecyclerView you have a separate Adapter extends RecyclerView.Adapter. you must implement Filterable so your adapter will look like
          Adapter extends RecyclerView.Adapter implements Filterable.
          in your adapter class implement getFilter() method logic to use getFilter method. There are many other examples to implement getFilter() logic I can’t mention all of them, Search for “Add a search filter on RecyclerView with Cards layout”

          Best regards,
          Beginners Heap

          • Muhammad Salma Nabila Alibasyi

            Nice, method getFilter works fine. Thankyou but when i use recyclerView.getAdapter().getList().get(position) instead of getItemAtPosition(), it’s still error (red warning). Here is my code:

            public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
            private RecyclerView recyclerView;
            private ArrayList data;
            private DataAdapter adapter;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            recyclerView.setAdapter(adapter);
            recyclerView.setOnClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView parent, View v, int position, long id){

            String text = (AndroidVersion) recyclerView.getAdapter().getList().get(position); Toast.makeText(getApplicationContext(), text,
            Toast.LENGTH_SHORT).show();
            }
            });
            initViews();
            }

            private void initViews(){
            recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setHasFixedSize(true);
            loadJSON();
            }
            private void loadJSON(){
            OkHttpClient.Builder client = new OkHttpClient.Builder();
            client.readTimeout(60, TimeUnit.SECONDS);
            client.connectTimeout(60, TimeUnit.SECONDS);
            Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(“http://192.168.1.14”)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
            RequestInterface request = retrofit.create(RequestInterface.class);
            Call call = request.getJSON();
            call.enqueue(new Callback() {
            @Override

            public void onResponse(Call call, Response response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList(Arrays.asList(jsonResponse.getPerson()));
            adapter = new DataAdapter(data);
            recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call call, Throwable t) {
            Log.d(“Error”,t.getMessage());
            }
            });
            }

          • Beginners Heap Free Tutorials

            Sorry about the previous answer that misguided for getting clicked item Text. use the below code to get the text of the selected TextView of the Card in RecyclerView.

            Text_View_Id is the id of the TextView in the card.

            int itemS=recyclerView.getChildAdapterPosition(v);

            RecyclerView.ViewHolder viewHolder =recyclerView.findViewHolderForAdapterPosition(itemS);

            TextView Text = (TextView) viewHolder.itemView.findViewById(R.id.Text_View_Id);

            String SelectedItem=(String) Text.getText();

            Toast.makeText(MainActivity.this, SelectedItem, Toast.LENGTH_SHORT).show();

            Hope that it will help.

            Best regards,
            Beginners Heap.

  • dev Programmer

    thank you But i want explain with data from WebService

  • Tayyab Qurban

    Thank you guys for sharing great information for newbies.