Adding search functionality to listview will filters the list data with a matching string, hence provides user an easy way to find the information he needs. In this tutorial i am discussing how to enable search filter to android ListView.

Download Code

1. Create a new project in Eclipse File New β‡’ Android β‡’ Application Project and fill the required details.
2. Create required files needed to generate a listview. I am using my default activity_main.xml as listview and created a new xml file for single listitem named list_item.xml. Also make sure that you have created a EditText above the listview which will be used to search the listview.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <!-- Editext for Search -->
    <EditText android:id="@+id/inputSearch"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:hint="Search products.."
    	android:inputType="textVisiblePassword"/>
 
	<!-- List View -->
    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
 
</LinearLayout>

list_item.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="match_parent"
    android:orientation="vertical" >
    
    <!-- Single ListItem -->
    
    <!-- Product Name -->
    <TextView android:id="@+id/product_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold"/>    

</LinearLayout>

3. Now open your MainActivity.java and paste the following code to create a simple ListView. In the following code i stored all the list data in an array called products[] and attached to listview using simple ArrayAdapter.

package com.androidhive.androidlistviewwithsearch;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
	
	// List view
	private ListView lv;
	
	// Listview Adapter
	ArrayAdapter<String> adapter;
	
	// Search EditText
	EditText inputSearch;
	
	
	// ArrayList for Listview
	ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Listview Data
        String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
        						"iPhone 4S", "Samsung Galaxy Note 800",
        						"Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
        
        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        
        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);       
        
    }
    
}
android listview search

Enabling Search Functionality

4. Search functionality can be enabled by writing simple lines of code. All you need to do is adding addTextChangedListener to EditText. Once user enters a new data in EditText we need to get the text from it and passing it to array adapter filter. All the following code in your MainActivity.java

        inputSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
				// When user changed the Text
				MainActivity.this.adapter.getFilter().filter(cs);	
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub							
			}
		});

5. Finally add the following property in your AndroidManifest.xml file to hide the keyboard on loading Activity.

android:windowSoftInputMode="stateHidden"

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.androidlistviewwithsearch"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
android listview search filter

Final Code:

package com.androidhive.androidlistviewwithsearch;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
	
	// List view
	private ListView lv;
	
	// Listview Adapter
	ArrayAdapter<String> adapter;
	
	// Search EditText
	EditText inputSearch;
	
	
	// ArrayList for Listview
	ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Listview Data
        String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
        						"iPhone 4S", "Samsung Galaxy Note 800",
        						"Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
        
        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        
        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);
        
        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
				// When user changed the Text
				MainActivity.this.adapter.getFilter().filter(cs);	
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub							
			}
		});
    }    
}
This image is for thumbnail purpose.
android listview search filter
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • monch

    Hi! when I do -ListView.setOnItemClickListener ….. it’s shows the old data from listview and not the data I was just filtered… how can I get the new data listView???

  • revathy

    thank u for ur tutorials ravi..it helped me a lot in my project…

    I need a help to implement the above code…In my case the content of list view is retrieved from databse(I refered your tutorial http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ for that).What i need is to update my list view content on a button click

    the code I have written will create a new ListView with updated content on each button click and display it below the previous ListView.Which I need to correct.

    • amit kumar

      hi.. i m a using this code but one problem occur actually i m a write the edit text they are filter the item but send the data before filtering..
      i.e. list item:
      12
      13
      14
      15
      filter item: 15
      and 15 become no first and i m a click on no 15 that show the data of no 12 first position in list view please help i m a click on no 15 then show data on no 15 after filtering

      • amit kumar

        its a code:

        inputSearch.addTextChangedListener(new TextWatcher() {

        @Override

        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

        // When user changed the Text

        List.this.adapter.getFilter().filter(cs);

        }

        @Override

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,

        int arg3) {

        // TODO Auto-generated method stub

        }

        @Override

        public void afterTextChanged(Editable arg0) {

        // TODO Auto-generated method stub

        }

        });

        lv.setOnItemClickListener(new OnItemClickListener() {

        @Override

        public void onItemClick(AdapterView arg0, View v, int po,

        long arg3) {

        mp.start();

        Intent i=new Intent(List.this,VocabbAC.class);

        i.putExtra(“AS”, it1[po]);

        startActivity(i);

        }

        });

  • Awesome tutorial… It has really helped me. @ravi! Please keep posting more stuff…

  • Hi guys I’d like to create two spinner widget, which will be connected to each other.
    For example the first spinner will have the continents (America,europe,Asia etc.).

    Supposed that someone choose Europe from the first spinner, then the
    european countries to be displayed to the second spinner. Another
    example is: if someone choose “America” for his first selection then the
    American countries to be available to the second spinner. pls ravi help me out my id is manjunath.c59@gmail.com

  • Greg

    Apply cold water to burned area..

  • Becky Johns

    Its incomplete code…..why have you not given code for getFilter() method?

    • Rishil

      Same problem for me..Have you found any solution ?

  • Ashwini

    how to add an icon in the listview for each rows

  • Gaurang

    I have same problem ! any idea

    • Anees

      lv.setOnItemClickListener(new OnItemClickListener() {

      public void onItemClick(AdapterView parent, View view,

      int position, long id) {

      // selected item

      // String product = ((TextView) view).getText().toString();

      String product=lv.getItemAtPosition(position).toString();

      // Launching new Activity on selecting single List Item

      Intent i = new Intent(getApplicationContext(), SingleListItem.class);

      // sending data to new activity

      i.putExtra(“product”, product);

      startActivity(i);

      }

      });

      • jeremy

        My issue is im trying to get the searched items actual array position to display correct items on next activity how do I get that actual array position im stumped..

  • Nico

    love it thank you!

  • Rohit

    Hi thanks a Lot for awesome tutorial!

    I was wondering how to do it with the help of search widget as i suppose it does not have addTextChangedListener … Can you provide some hint .. I am really stuck .. I have implemented search widget in action bar btw…

  • Rheyan Dizon

    Nice, Great Tut. but i was wondering how i can put another page in each item, example: when i click Dell Inspiron, it will go to dell inspiron page that has its definitions/descriptions

    Thanks for your help

    • uno_xx

      It is very simple, put switch cases in the listadapter ‘s onitemclick listener and in each switch cases, start an activity of your choice πŸ˜‰
      Edit :

      Try this, worked for me:

      lv.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView parent, View view,int position, long _id) {
      String values = adapter.getItem(position);

      // TODO Auto-generated method stub
      Intent i =null;

      if (values==”1,000 Hours”) {
      i=new Intent(Allsongs.this, Thousandhours.class);
      startActivity(i);}
      if (values==”16″) {
      i=new Intent(Allsongs.this, Sixteen.class);
      startActivity(i);}
      if (values==”2000 Light Years Away”) {
      i=new Intent(Allsongs.this, Lightyears.class);
      startActivity(i);}
      if (values==”21 Guns”) {
      i=new Intent(Allsongs.this, Guns.class);
      startActivity(i);
      }

      }
      });

      • Luis

        Man, I cannot thank you @vishalnehra:disqus and @ravi8x:disqus enough, you guys were really helpful, this was exactly what I needed! List + action to it’s values.

        • uno_xx

          Pleasure to help you πŸ™‚

  • BONG

    I REALLY REALLY LIKE IT!!

    • bong

      but i have another question

      i want to ,, when i click the word it will open new xml file how can i do that reply please

  • falahgs

    thanks for this great post ….
    great information for me …

  • Siddharth

    can please give a tutorial on how to attach search bar with database means if we search something than it will retrieve it from database and give the result..

  • Deobrat Nayak

    Very helpful

  • Rishi Srivastava

    How to get a video attached with a hashtag into a search bar for the user to serarch the video from there?

  • kevin

    This is great. However, there is one thing that I don’t understand. The full search capability (letters that start in the middle), works sometimes and not others. For example, type s and you’ll see it properly finding all listitems that have s. Type e, and you don’t see the same result?!!

  • Lynn Houthuys

    I assume you normally use

    String product = products[position];

    to determine which product was selected ?

    If that’s the case just replace it by:
    String product = adapter.getItem(position);

  • Hi.
    How to add the search in Action Bar instead?!!

  • avnish rathod

    hello sir..
    i have custom array adapter for listview…in array adapter bind two textview (id,name) that comes from databases…i want to implement search function on listview how to implement?

  • Edward James Woollard

    This is exactly what I want to know. Ravi please help us!

  • paijo

    simply use this

    lv.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView parent, View view,
    int position, long id) {
    // TODO Auto-generated method stub

    String products = adapter.getItem(position);
    Intent i =null;

    if (products==”Dell Inspironi”) {
    i=new Intent(Product_Type.this, DellInspironi.class);
    startActivity(i);}
    if (products==”HTC One X”) {
    i=new Intent(Product_Type.this, HTCOneX.class);
    startActivity(i);}
    if (products==”HTC Wildfire S”) {
    i=new Intent(Product_Type.this, HTCWildfireS.class);
    startActivity(i);}
    }

    });

    • uno_xx

      I worked! Thank you very much πŸ™‚

  • Caio Lins

    Hello Ravi, I am trying to implement this using a list that is inside a Fragment…
    In other words my Fragment is visible and I want to make this filter connection between an EditText on my main Activity and my ListView within my Fragment. How can I do this? Ty

  • Rishil

    Can I use this code in Expandable list view ?

  • abc

    Thanks…working perfeclty

  • Zahid Hasan

    I have a custom ListView adapter. How do I achieve the above?

  • uno_xx

    Prevent using android:inputType=”textVisiblePassword” in edittext
    It prevents using swipe feature in soft keyboard!

  • Guest

    hello, i not using array adapter, can after i implement your code, i having not accurate output
    can you help me on this? below is my coding

    CustomListView testingAdapter;

    lv = (ListView) findViewById(R.id.lvEditSavingList);
    inputSearch = (EditText) findViewById(R.id.inputSearch);
    loadListViewData();

    private void loadListViewData() {
    // TODO Auto-generated method stub
    UnderControlDb db = new UnderControlDb(getApplicationContext());
    String[] info = db.MySavingShowData();
    int counter = info.length;
    Integer[] imageID = new Integer[counter];
    for(int i=0;i<counter;i++){
    imageID[i] = R.drawable.edit_notes_list;
    }
    testingAdapter = new CustomListView(MySaving.this, info, imageID);
    lv.setAdapter(testingAdapter);
    }

    another class

    public class CustomListView extends ArrayAdapter{
    private final Activity context;
    private final String[] data;
    private final Integer[] imageId;
    public CustomListView(Activity context,String[] data, Integer[] imageId) {
    super(context, R.layout.my_saving_list, data);
    this.context = context;
    this.data = data;
    this.imageId = imageId;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView= inflater.inflate(R.layout.my_saving_list, null, true);
    TextView txtTitle = (TextView) rowView.findViewById(R.id.tvSavingListView);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.imgS);
    txtTitle.setText(data[position]);
    imageView.setImageResource(imageId[position]);
    return rowView;
    }
    }

    please help me on this and email me jiunhaw924@hotmail.com, thank you in advance.

  • JotaPardo

    Hello, I have a Question. Can I implement this code using an andorid Fragment in spite of Activity? Problem is the line ” MainActivity.this.adapter.getFilter().filter(cs); ” give me an error: NullPointerException.

    I use all the code you have in my fragment activity, including

    // Listview Adapter

    ArrayAdapter adapter;

    // Search EditText

    EditText inputSearch;

    // ArrayList for Listview}

    and

    inputSearch = (EditText) view.findViewById(R.id.inputSearch);

    inputSearch.addTextChangedListener(new TextWatcher() {

    @Override

    public void onTextChanged(CharSequence cs, int start, int before, int count) {

    // When user changed the Text

    //adapter.getFilter().filter(cs);

    Log.w(“onTextChanged”,”Here”);

    try{

    SearchFragment.this.adapter.getFilter().filter(cs);

    Log.i(“Frame”, “yeahhh”);

    }

    catch(Exception e){

    Log.e(“Frame”, e.toString());

    }

    }

    Thanks a lot.

    • Varun Barve

      SearchFragment.this.getActivity().adapter.getFilter().filter(cs);

  • srujith

    how to add details of that device so that if we click on that we should get details

  • Nopled

    woh! that reminds me again to check the documentation before going deeply in implementing anything. I was working on this from scratch unaware of the existence of such filtering API. yet this solution not retrieving the whole list that contains the ‘keyword’, instead it retrieves a list of the strings that start by the ‘keyword’. thank you so much!

  • Nasif Ahmed

    I have a problem

    Example:
    String[] products = { “One”, “Two”,
    “Three”, “Four”, “Five”, “Six”,
    “Seven”,

    “Eight”,
    “Nine”, “Ten” };

    Elemet —– position

    One ——— 0

    Two ——— 1

    Three ——- 2

    Forur ——– 3

    ……………..

    ……………………….

    ………………………………….

    Now I search for f

    Then Four and five will come in list view

    Now

    Elemet —– position

    Four ——– 0

    Five ——— 1

    So position is changed. But I need position before list
    view change. Because I will pass this position another activity. Then that activity
    access a database by this position.

    What Can I don now?

    Please Help me.

    • Send me code I will check out your issues than I vil rectify and provide you solution.

    • Toumash

      get an long ID instead of position

  • Kelvin

    Thanks Ravi for the tutorial,

    I am getting the error bellow when I type on the search textview

    05-11 16:12:34.026: E/AndroidRuntime(9989): java.lang.NullPointerException

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.widget.AdapterView.checkFocus(AdapterView.java:715)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.widget.AdapterView$AdapterDataSetObserver.onInvalidated(AdapterView.java:838)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.widget.AbsListView$AdapterDataSetObserver.onInvalidated(AbsListView.java:7622)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.database.DataSetObservable.notifyInvalidated(DataSetObservable.java:50)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.widget.BaseAdapter.notifyDataSetInvalidated(BaseAdapter.java:59)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.widget.ArrayAdapter$ArrayFilter.publishResults(ArrayAdapter.java:514)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.os.Handler.dispatchMessage(Handler.java:99)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.os.Looper.loop(Looper.java:137)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at android.app.ActivityThread.main(ActivityThread.java:5419)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at java.lang.reflect.Method.invokeNative(Native Method)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at java.lang.reflect.Method.invoke(Method.java:525)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

    05-11 16:12:34.026: E/AndroidRuntime(9989): at dalvik.system.NativeStart.main(Native Method)

    Bellow is my code

    ArrayList<HashMap> productList;

    String products[] =db.productname();

    final ListView lv = (ListView) dialog.findViewById(R.id.list_view);

    final EditText inputSearch = (EditText) dialog.findViewById(R.id.inputSearch);

    // Adding items to listview

    adapter = new ArrayAdapter(getActivity(), R.layout.list_item, R.id.product_name, products);

    adapter.notifyDataSetChanged();

    adapter.getCount();

    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView myAdapter, View myView, int myItemInt, long mylng) {

    String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

    //Toast.makeText(getActivity(), selectedFromList,Toast.LENGTH_SHORT).show();

    Et_search.setText(selectedFromList);

    dialog.dismiss();

    }

    });

    inputSearch.addTextChangedListener(new TextWatcher() {

    @Override

    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

    // When user changed the Text

    ManualSaleFragment.this.adapter.getFilter().filter(cs);

    }

    @Override

    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,

    int arg3) {

    // TODO Auto-generated method stub

    }

    @Override

    public void afterTextChanged(Editable arg0) {

    // TODO Auto-generated method stub

    }

    });

    dialog.show();

    }

    });

    return rootView;

    }

    }

  • vaibhav

    how to do same thing with data coming from a link in json formate…please help me…n thanx in advance

  • vikash

    sir how to make bold text on listview that i typed in EditText ( inputSearch in your case )??

    • Just go in xml file and use Style Tag for Bold and Italic.

  • Minal Kishnani

    Thanks

  • Guest

    Hi I loaded my datas with json from internet what I’m gonna change in variables

  • Ali Nawaz

    hii.. iwant to load data in searchable list view from sqlite data base but i can’t get it…any toutorial/help??thanks!!

    • irshad

      i m having the same problem.. did u get any solution of this?

    • Creating a CustomBaseAdapter may help you, think so.

  • thischickcalledcandice

    I have a adapter which accepts a list of (With a question and answer). the listview then inflates the custom list. If I use this code, what will be filtered? Everything in that list (Question and answer) or how could adapt it to search only on the question? Thanks so much!

  • mob

    hello bro & everyone

    how i can adding ” Listview Header (Two or More) In my app “

  • Dyego

    Thanks for the tutorial, I thought it would be pretty hard =P

  • abdul

    i need to implement search suggestions from server in my app?

  • Heitor Colangelo

    Thank you!
    I’ve been looking for how to do this for 1 day!

  • abitha

    hey thanks this was so so helpful !

  • Ashraf Reto

    thanks this was so so helpful !

  • balazack

    It’s really awesome tutorial.., thanks this was so helpful to my project:)

  • Kostas

    Hello Ravi awesome tutorial….but i was wondering how i can do the same thing but with a custom listview adapter tha implements imageview and more than one textviews…can u make a tutorial for this??

  • alex

    hi
    i have a problem
    search.java code is :

    package ir.korang.powerelectron.AndroidTrainingReference;

    import android.app.Activity;
    import android.app.AlertDialog;

    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.Button;

    public class Contact extends Activity {

    WebView webView=null;
    AlertDialog alertDialog=null;
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.contact);

    webView = (WebView) findViewById(R.id.webView1);

    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl(“file:///android_asset/quis.htm”);
    webView.setWebViewClient(new WebViewClient());
    @SuppressWarnings(“unused”)
    class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return true;
    }
    }
    Button Refresh = (Button) findViewById(R.id.button2);
    Refresh.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    webView.loadUrl( “javascript:window.location.reload( true )” );
    }
    });
    Button Home = (Button) findViewById(R.id.button1);
    Home.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    Contact.this.webView.loadUrl(“file:///android_asset/quis.htm”);
    }});
    Button Back = (Button) findViewById(R.id.but3);
    Back.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    if(webView.canGoBack()){
    webView.goBack();
    return;
    }
    }});
    Button Forward = (Button) findViewById(R.id.but4);
    Forward.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    if(webView.canGoForward()){
    webView.goForward();
    return;
    }
    }});

    }
    }

    when i run this activity occur a error.error log is :

    12-03 16:07:50.879: E/AndroidRuntime(4330): FATAL EXCEPTION: main
    12-03 16:07:50.879: E/AndroidRuntime(4330): Process: ir.korang.powerelectron.AndroidTrainingReference, PID: 4330
    12-03 16:07:50.879: E/AndroidRuntime(4330): java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.korang.powerelectron.AndroidTrainingReference/ir.korang.powerelectron.AndroidTrainingReference.Contact}: java.lang.NullPointerException
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.access$800(ActivityThread.java:135)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.os.Handler.dispatchMessage(Handler.java:102)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.os.Looper.loop(Looper.java:136)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.main(ActivityThread.java:5001)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at java.lang.reflect.Method.invokeNative(Native Method)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at java.lang.reflect.Method.invoke(Method.java:515)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at dalvik.system.NativeStart.main(Native Method)
    12-03 16:07:50.879: E/AndroidRuntime(4330): Caused by: java.lang.NullPointerException
    12-03 16:07:50.879: E/AndroidRuntime(4330): at ir.korang.powerelectron.AndroidTrainingReference.Contact.onCreate(Contact.java:52)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.Activity.performCreate(Activity.java:5231)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
    12-03 16:07:50.879: E/AndroidRuntime(4330): … 11 more
    12-03 16:07:58.475: I/Process(4330): Sending signal. PID: 4330 SIG: 9
    12-03 16:18:16.691: D/dalvikvm(4442): GC_FOR_ALLOC freed 45K, 3% free 3543K/3652K, paused 4ms, total 5ms
    12-03 16:18:16.691: I/dalvikvm-heap(4442): Grow heap (frag case) to 9.010MB for 5760012-byte allocation
    12-03 16:18:16.723: D/dalvikvm(4442): GC_FOR_ALLOC freed <1K, 2% free 9168K/9280K, paused 25ms, total 25ms
    12-03 16:18:16.947: D/(4442): HostConnection::get() New Host Connection established 0xb7f36090, tid 4442
    12-03 16:18:20.867: D/dalvikvm(4442): GC_FOR_ALLOC freed 5K, 1% free 9201K/9280K, paused 3ms, total 4ms
    12-03 16:18:20.875: I/dalvikvm-heap(4442): Grow heap (frag case) to 12.671MB for 3804812-byte allocation
    12-03 16:18:20.883: D/dalvikvm(4442): GC_FOR_ALLOC freed <1K, 1% free 12916K/12996K, paused 8ms, total 8ms
    12-03 16:18:21.011: D/dalvikvm(4442): GC_FOR_ALLOC freed 1K, 1% free 15952K/16036K, paused 3ms, total 3ms
    12-03 16:18:29.923: D/AndroidRuntime(4442): Shutting down VM
    12-03 16:18:29.923: W/dalvikvm(4442): threadid=1: thread exiting with uncaught exception (group=0xa4caeb20)

    please help me.
    what is problem ?

  • jabeelee

    how to make items here clickable? pls. help πŸ™

    • Ryan Smith

      Add onClicklistener..

  • King Yaya

    how to make the java array retrieve from mysql database?

  • Mayank Tripathi

    very nice article….it working fantastic

  • ranjith

    simple and effective..can I add into actionbar?

  • aofxta

    If a Custom ListView?

    • Ryan Smith

      Would be a Custom Adapter i presume?

  • Ravi, I’ve a doubt . What is the use of the “ArrayList<HashMap> productList” in your code.

  • PraiserJweller

    i used setOnClick method to link my array items to html files that are stored in asset folder but there is a problem and that is when i search something, it finds correct but when i click on item it direct to wrong position and show wrong html file. i used:
    myIntent.putExtra(“key”,position); code in listview activity and i used:
    int pos = getIntent().getIntExtra(“key”, 0);
    if (pos == 0) {
    web2.loadUrl(“file:///android_asset/osteo/osone.html”);
    }…

    i’m stuck in this position.always wrong result for search.
    please if it was possible for you, write for me right code or give me solution.
    thank you for giving your time to me.

  • Kishore Kumar Korada

    Hii,
    It works pretty well for my but the problem what I’m facing is, when ever I search it searches from left to right characters but what if I want to search based on last 4 characters? How to achieve that?

    • Junior Frogie

      use like %%

  • Jose Magalhaes

    good, I tested this code and it worked fine, the programmer this parabens …

    In many sites I’ve seen on the net, this is the best and which explains better …

    Many Congratulations, I hope to continue for information …

    5 stars …

  • R42

    Anyone know how to add another item there?

  • DomenicoButtafarro

    Hi i have this, please can add for me filter for search?

    package com.androidbegin.jsonparsetutorial;

    import android.app.Activity;

    import android.app.ProgressDialog;

    import android.os.AsyncTask;

    import android.os.Bundle;

    import android.util.Log;

    import android.widget.EditText;

    import android.widget.ListView;

    import org.json.JSONArray;

    import org.json.JSONException;

    import org.json.JSONObject;

    import java.util.ArrayList;

    import java.util.HashMap;

    public class MainActivity extends Activity {

    // Declare Variables

    EditText editsearch;

    JSONObject jsonobject;

    JSONArray jsonarray;

    ListView listview;

    ListViewAdapter adapter;

    ProgressDialog mProgressDialog;

    ArrayList<HashMap> arraylist;

    static String RANK = “rank”;

    static String COUNTRY = “country”;

    static String POPULATION = “population”;

    static String FLAG = “flag”;

    private EditText et;

    private ListView lv;

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Get the view from listview_main.xml

    setContentView(R.layout.listview_main);

    // Execute DownloadJSON AsyncTask

    new DownloadJSON().execute();

    }

    // DownloadJSON AsyncTask

    private class DownloadJSON extends AsyncTask {

    @Override

    protected void onPreExecute() {

    super.onPreExecute();

    // Create a progressdialog

    mProgressDialog = new ProgressDialog(MainActivity.this);

    // Set progressdialog title

    mProgressDialog.setTitle(“Android JSON Parse Tutorial”);

    // Set progressdialog message

    mProgressDialog.setMessage(“Loading…”);

    mProgressDialog.setIndeterminate(false);

    // Show progressdialog

    mProgressDialog.show();

    }

    @Override

    protected Void doInBackground(Void… params) {

    // Create an array

    arraylist = new ArrayList<HashMap>();

    // Retrieve JSON Objects from the given URL address

    jsonobject = JSONfunctions

    .getJSONfromURL(“http://quizmessina.altervista.org/R.txt”);

    try {

    // Locate the array name in JSON

    jsonarray = jsonobject.getJSONArray(“worldpopulation”);

    for (int i = 0; i < jsonarray.length(); i++) {

    HashMap map = new HashMap();

    jsonobject = jsonarray.getJSONObject(i);

    // Retrive JSON Objects

    map.put(“rank”, jsonobject.getString(“rank”));

    map.put(“country”, jsonobject.getString(“country”));

    map.put(“population”, jsonobject.getString(“population”));

    map.put(“flag”, jsonobject.getString(“flag”));

    // Set the JSON Objects into the array

    arraylist.add(map);

    }

    } catch (JSONException e) {

    Log.e(“Error”, e.getMessage());

    e.printStackTrace();

    }

    return null;

    }

    @Override

    protected void onPostExecute(Void args) {

    // Locate the listview in listview_main.xml

    listview = (ListView) findViewById(R.id.listview);

    // Pass the results into ListViewAdapter.java

    adapter = new ListViewAdapter(MainActivity.this, arraylist);

    // Set the adapter to the ListView

    listview.setAdapter(adapter);

    // Close the progressdialog

    mProgressDialog.dismiss();

    }

    }

    }

    • Dammalapati sairam

      Hello DomenicoButtafarro,have you got the solution……………….

  • Hunter

    Thx for ur great tutorials….!!!!!!

  • JoΓ£o Nora

    Hello, thanks a lot for this tutorial, it’s perfect! but i’ve a question.

    with this code i can search in all adapter, but if i only want to search in 1 parameter?

    like for exemple

    adapter = new SimpleAdapter(
    SearchActivity.this,
    searchList,
    R.layout.list_products,
    new String[] { TAG_ID,
    TAG_TITLE,
    TAG_CATEGORY,
    TAG_DESCRIPTION,
    },
    new int[] { R.id.productID,
    R.id.productTitle,
    R.id.productCategory,
    R.id.productDescription,
    }
    );
    lv = getListView();
    setListAdapter(adapter);

    with tthis line of code i search in all adapter:
    ((SimpleAdapter)SearchEbookActivity.this.adapter).getFilter().filter(cs);

    what if i only want to search for TAG_DESCRIPTION ?

    how can i filter that?

    thanks in advance for the help!

  • Joy

    Simple Tutorial..Works Perfectly..I do have a Query Suppose i want to add search icon what shoud i do? i mean when i type search button should hide in the box and delete button on right side to clear if i typed wrong.Thanks in Advance…
    Keep Going…

  • nikhil vedurumudi

    Hi , this thing works perfectly. Can you tell me how to port the same onto a fragment. Should we be following the same steps or will there be any modifications that are needed to be made.

    Thanks,
    Nikhil

    • I too don’t know. May be you can try it once, then you’ll get to know.

      • nikhil vedurumudi

        I have tried it. The following code in onCreateView would do the job for us.

        ListView lv;

        EditText inputSearch;

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_search_conversations, container,false);

        lv =(ListView)rootView.findViewById(R.id.list_convo);

        inputSearch = (EditText)rootView.findViewById(R.id.inputSearch);

        String[] values = new String[] { “String1”, “String2”, “String3” };

        adapter = new ArrayAdapter(getActivity(),

        R.layout.list_item,R.id.lblListItem, values);

        lv.setAdapter(adapter);

        return rootView;

        }

        • Mrr Malik

          i have created list without using setcontentview(),i have extended listactivity is this code applicable for my list?

  • Hale Γ‡imen

    I didn’t understand. Where is the ‘R.layout.list_item, R.id.product_name’ ?
    Image following here;
    http://i.hizliresim.com/DM2ljo.png

  • zalak

    I am working on android app in which data are bind in listview using ListAdapter. I want to put search functionality in it. I used your code but getfilter method can’t be used for ListAdapter. So Can you help me Ravi??

  • Viral Agrawal

    Thanks. It works perfectly well.

  • pk

    Thanks. Great help for beginners.

  • Shankar Johnny

    Ravi bro , im from warangal .your tuts are awesome and usefull
    I want to know how to make a listview item clickable and when clicked a new activity should open,help please.

  • Gaurav meghanathi

    it is not filtering character sequence wise. i tried text search i the string gave me the name dell inspiration iphone 4s ,iphone 5,iphoe 5c but didn’t show me the HTC Wildfire S,HTC Sensation XE how can i slove…?

  • Bhavik Shah

    How can i get the text of the item on which i clicked and how can i add a drawable icon on each list item which is dynamically fetched from a server?? I achieved populating the listview with dynamic data from server

  • Pooja

    trying to subscribe for last 2 days, not getting any activation email. Please email me the code.

  • Satosh Dawanse

    someone please tell me the purpose of ArrayList<HashMap> productList;

    • Amol Wangate

      we can use more than one objects in of ArrayList<hashmap> .
      like you have contacts in your phone, which contain “person name” as well as “phone no”

  • Ananda Sanhka

    Hi Travi, you tutorial is alright, but what happens when i want to add multiple string array, how do i implement it, so i can search from any of the array.

  • Okechukwu Eze

    i have been trying to add dis nice piss of code to my ListView in a Fragment but it has not been able to work for me as it keeps flagging :: Cannot resolve method ‘getFilter()’ and i dont know why or how to go about solving using this search inside a Fragment

  • Jhay

    is it also applicable to grid views ?

  • gowtham nimmagadda

    Is This ListView works only for Single Text ?

    I have an image two text views and a button as group and can i show them in List View,

  • Brewh

    Good tutorial sir , how to change search string to search by number sir ? thank you

  • Gaurav Wadhwani

    Good tutorial sir , will you tell me how do i search by sub-string?

  • mikko

    sir, how to fetch data from sql database browser to listview?

  • ABHISHEK PANDEY

    how to invoke product list from database for searching

  • dana riano

    hello sir, how can I make the items clickable then it will send me into another activity

    • Praveen Bhati

      Just set OnItemClickListener to listview object then in onItemClick() method open another activity, if you want to send data to another activity you can use
      intent.putExtra(KEY,Valye);

  • cihan erdogan

    Hi Ravi, if we put a checkbox over the list items how can we use a search filter about that ?

    • cihan erdogan

      Anyway I made it :))

  • Nicholas Webb

    This is the first success I have had so far as far as properly filtering my ListView, however, I have it set with an intent.putExtra, example:

    intent.putExtra(“name”, jsonArray.optJSONObject(arg2).getString(“name”));

    and though it filters exactly as I’d like, when I tap an item with this onItemClickListener,
    I end up with the original entry details in the new view.

    is there a simple way to alter the intent.putExtra based on the newly returned filtered list?

    • Hans Herrmann

      do you fixed it?

  • Mayank

    I have an Image as well as text in the list view and I am using your code .. but i face error while searching. It says

    An exception occured during performFiltering()!

    java.lang.ClassCastException: android.graphics.Bitmap cannot be cast to java.lang.String

    Do you have any solution to this. please help me .

    • rihab majdoubi

      Hello , i have the same probleme did you find a solution ?? πŸ™‚

  • vishal sharma

    how can i link this searchbox with google

  • dipti

    hello Ravi sir. I am having some querries for search with listview…
    Actually I wann show list of filtered contacts as per textchanges. I want to popup the whole filtered contactlist on textchange.But the restriction is that i don.t wann show all contacts in list .Like when you compose a msg on android phone. You type name in user filed. as per that field the filtered contacts would appear without showing all contacts of mobile in listview Plz help me…

  • Vinayak Parab

    How To Add Two TextView In This Example

    But Search Only One String.

    Thank You

  • Gowtham Nimmagadda

    Hi Android Hive,

    Is there any chance to get single Product object assigned to a particular ListView Element.. I need to get the product object on click of the ListView Element.Thank You in advance

    • devansh

      you can use switch case

      • Gowtham Nimmagadda

        I haven’t got clarified. Is there any example to explain. A link to that example is appreciated.

        I need all the variables of product object allocated to a particular ListView element clicked.

        Don’t know if i’m disturbing you.

        Thank You

        • zeffah

          Please use custom list adapter which extends baseAdapter, so that you populate your list from it. On click list item, do “adapter.getItem(position)”…That will help

          • Gowtham Nimmagadda

            Yep. I got it. Thank You

  • Joni Fritz

    That was quite helpful, Sir!

  • Jaydeep Dhamecha

    Hi Android Hive,

    In this case autocompletetextview using recyclerview adapter it’s that possible?

  • Linu S

    I have to add filter the data retrieved from mysql using json array…
    I add the searchView filter.. but when type on the search box the app stops with the eror mssage.

  • Ethan

    I used this code in my app MainActivity.this.adapter.getFilter().filter(cs); for searching on my ListView.When my class extends Activity it works correctly, but when the class extends ListActivity it doesn’t search.How can I search on a ListView when the class extends ListActivity?

  • Kevin Camuendo Pineda

    How can i do this by retrieving data from local server e.g. phpmyadmin

  • sujitha reddy

    sir can you help me…… i need same code but populating the listview using JSON…similarly searching also same ….
    i try your code in list view populate (JSON) but one error is happens every time can you solve it otherwise guide me….

    • What is the error?

    • sujitha reddy
      • You need to give me the error report. I won’t be running your project.

        • sujitha reddy

          its not error its exception java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String java.lang.Object.toString()’ on a null object reference

    • ami vadera

      hey i performed this with JSON and list view

      • sujitha reddy

        I fine my way ….

  • Jake

    how can i use this with the listview using JSON? im using “extends ListActivity”

  • ami vadera

    how to use it with custom adapter with Jason ,because there is problem in filtering.

  • saurabh sarpotdar

    Hi ravi…I used a custom adapter for my listview because I wanted to achieve lazyloading in it… So with your code it is not searching in the listview.. I did check the custom adapter class it does extend arrayadapter..so why do you think it is not searching in listview..? any guesses

    • Sourabh Shastri

      Hey Saurabh
      I have the same issue as your’s.
      Please assist me if you have found the solution.

  • sd

    how can I highlight the searched text?

    • uzma khan

      use border line

  • hello

    how to handle listview itemclick event

    • Rashid Fahim

      lv.setOnItemClickListener(new
      Put this line and after “new” hit CTRL+Space and select OnItemClickListener and it will create full method for you.

  • Obaiz Ali

    how to search if I am using FirebaseListAdapter ?

  • Ashish

    When All data are dynamically comes Through MySQL server How can we Add Text watcher in android studio

    • Rashid Fahim

      Ashish bro, you are showing that MySQL data in listview?
      If yes then you just need an EditText and you need to add Text watcher to that EditText and then use adapter’s filter method.

      • Ashish

        I am Write Like Your Code String products[] = {“Dell Inspiron”, “HTC One X”}; but i have problem my data comes into database with the help of php . How can I Use My data . When I am Insert Selected Data Then Show only One Last value . please Help Me. How can I fix This Problem.

  • Mayank Aggarwal

    I am getting an error of not being able to resolve the adapter name in the line

    “MainActivity.this.adapter.getFilter().filter(cs);”

    Why am I getting that error?

    • Rashid Fahim

      Bro, you have to pass your adapter name here which you used to put data in listview and remember, you have to initialized this adapter first. You can do this in one line like this.
      ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item, R.id.product_name, products);

  • suresh

    how to create global search

  • Ucen

    Thanks Bro ! Simple !! Awesome !!