Add Searching in List View.

Search Functionality the best thing we use to find information fast and easy. well in your application if you have long list of information and you want provide search function in your application. it may affect your application credits. user get bored after so much scroll in list. So to add search functionality you have two option One is using Action bar search functionality and Second is alert box that ask for query and then you search on the basis of that. one main thing about this Search function is you have to use in built layout of list view in order to work it (My opinion). 

Steps
  • Create New Application and give name it ListViewSearch and Do next. 
    • minSdkVersion="17” 
    • targetSdkVersion="17". 
  • Give activity name – Main.java and main.xml. 
  • Go to main.xml and paste the below code.
Main.xml



    
    



Now Go to menu > main.xml file and put below code in it.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        app:showAsAction="always|collapseActionView"
        android:icon="@android:drawable/ic_menu_search"
        android:id="@+id/menu_item_search"
        android:actionViewClass="android.widget.SearchView"
        android:title="Search"
        android:iconifiedByDefault="true"/>
</menu>

Action bar was introduce in Android 3.0 version so if you are creating app that works on gingerbread and all version you have to add search view above list view or you can use action bar sherlock. you can check out my tutorial on action bar sherlock for more.now go to your class file and put below code.
Main.java

package com.androprogrammer.app3;

import android.os.Bundle;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.text.TextUtils;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class Main extends Activity implements OnQueryTextListener{

 ListView lv;
 CustomAdapter adapter;
 String temp[] = {"Gplus","Facebook","Instagram","Linkdin","Pintrest","Twitter","Snapchat","Skype"};
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  lv = (ListView) findViewById(R.id.listView1);
  lv.setAdapter(new ArrayAdapter < string >(getApplicationContext(),android.R.layout.simple_list_item_1,temp));
  lv.setTextFilterEnabled(true);
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
        SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(this);

        return super.onCreateOptionsMenu(menu);
 }

 @Override
 public boolean onQueryTextChange(String newText)
 {
  // this is your adapter that will be filtered
      if (TextUtils.isEmpty(newText))
      {
            lv.clearTextFilter();
        }
      else
      {
            lv.setFilterText(newText.toString());
        }
        
      return true;
 }

 @Override
 public boolean onQueryTextSubmit(String query) {
  // TODO Auto-generated method stub
  return false;
 }

}

Screen Shot

As you can see your query display in below Box and it also filter your list view adapter. that's it now run your application and see it works with your tweak or not. if you have any query or problem with it post it in below comment box. i have solved many problems that are still on stack overflow and many forums. you can suggest or share this link with your friends.
if you like the blog subscribe to our blog or like us on facebook or Google+.
Keep coding..

Download Code

23 comments :

  1. How to hide that black box, which is displayed while typing query?

    ReplyDelete
    Replies
    1. It is by default with search view class. If you want to remove it you have to create other view that display search results and all.
      You can read more about it at...
      http://developer.android.com/guide/topics/search/search-dialog.html

      Delete
  2. can you please forward this code ZIP to me on my ID:-androidsmarter@gmail.com as it is not executable after doing copy paste as you told up.

    ReplyDelete
    Replies
    1. i have updated my article and added link for download project files.
      so check this out.

      Delete
  3. How to donwload your download link? It has many ilivid....

    ReplyDelete
  4. hello.

    as serious a tab of the onQueryTextCange actionbarActivity search.

    ReplyDelete
    Replies
    1. Hey
      I can't understand what you are trying to say.
      So can you clarify it.

      Delete
  5. Good day.
    how to open a new activity when i click one item on the list?

    ReplyDelete
    Replies
    1. Use on item click method of list view.

      Delete
    2. Like onListItemClick() ???

      Sorry for the question tho.
      im new on developing android apps :<

      thank you for help

      Delete
    3. Yes that method.
      In which you will get position and all.

      Delete
  6. I use custom list view.
    private ListView mListView = null;
    private ListViewAdapter mAdapter = null;
    mListView = (ListView) findViewById(R.id.listview);

    mAdapter = new ListViewAdapter(this);
    mListView.setAdapter(mAdapter);



    and your code... i copy and paste
    but no search........

    ReplyDelete
  7. Hey in custom adapter class you have to impliment onQueryTextChange() method. as you can see i have used array adapter, that's why i have implimented that method in main class.
    so according to your requirement you have to change this code.

    ReplyDelete
  8. Greetings to you.I have used similar code with custom list adapter with three text views and an image view as single list item.My problem is consider for example I have names like "Amith,Sumith,Subhash,Balu" when I type in search view as"Su" i am getting "Amith" and "Sumith" that is the first two items in my list not the exact data.So what need to do?Thanks in advance.

    ReplyDelete
    Replies
    1. its very odd behavior.
      can you post some code here so i can check and give you proper solution.

      Delete
  9. Kindly help with the customAdapters please, whenever i paste the code for the SetOnQueryChanged there is an error of incompatible types with the this argument of the setOnQueryListener underlined, lindly help

    ReplyDelete
    Replies
    1. Hey Sahil Aggarwal,
      Can you paste your code here so i can check it.
      please use pre tag to paste code or pastebin link.

      Thanks.

      Delete
  10. why why why. dismiss popup? i dont want to appear popup . pls help me.

    private void setupSearchView() {
    mSearchView.setIconifiedByDefault(false);
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setSubmitButtonEnabled(false);
    mSearchView.setQueryHint(getActivity().getApplicationContext().getString(R.string.main_list_search));
    }

    @Override
    public boolean onQueryTextChange(String newText) {


    if (TextUtils.isEmpty(newText)) {

    myList.clearTextFilter();
    } else {
    StoppingTask();
    myList.setSelectionAfterHeaderView();
    VehicleSensorAdapter adapter = (VehicleSensorAdapter) myList.getAdapter();
    adapter.getFilter().filter(newText);
    myList.setFilterText(newText.toString());
    }
    return true;
    }

    ReplyDelete
    Replies
    1. Hey ulaş erdegör,
      First of all what kind of data your binding through adapter ?
      i mean it is string or some kind of model, please let me so i can guide you further.

      Thanks

      Delete
  11. am using a ListView where each item has a corresponding checkboxes. I set up a editText to work as a search bar with addTextChangedListener. When using the search bar, the items displayed are reduced to those who fit the search, as expected.

    However, the items that were checked before the search are not necessarily still checked. The check mark is not carried with the item. For example, if I were to check only to first item on the list, then whatever my search is, the first item displayed (if any) will have that checkmark. Reciprocally, the items checked while in search will not be carried by the items.

    ReplyDelete
  12. how can used it online php file then search listview

    ReplyDelete
    Replies
    1. Hi mukesh,
      I can't understand everything what you are trying to say but if you are asking how can make web service call on search you can put that code in onQueryTextSubmit method.
      That will be called when user click on search icon in keyboard or enter icon in search bar.

      i hope this is what you want.

      Delete
  13. Hi please tell me simple way to hide the black box coming underneath

    ReplyDelete