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?

  • 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 …