Monday 26 August 2013

Android Search Functionality with ListView

Overview:

 In this tutorial i am showing that how to Adding search functionality to ListView and how can  filters the list data with a matching string,which provides user an easy way to find the information he needs from list. 



Why we need this search box with ListView?

Lets Suppose we have various item attached with listview,it may be more than 1k.So in this case we use search box to find the required item from listview,because this is not possible to scroll down the whole list to search the that item.
Lets takes a simple example to show the core concept behind this.
  • Create a new project in Eclipse File > New > Android Application Project and fill the required details.
  • 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 that is  mylist.xml. Also creating a EditText acting as a search box in this example.
Here is activity_main.xml file:

<?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" >
     
   
    <EditText android:id="@+id/Search_box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Search a Item from ListView"
        android:inputType="textVisiblePassword"/>
  
   
    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
  
</LinearLayout
mylist.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" >
     
   
     
   
    <TextView android:id="@+id/List_item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="12dip"
        android:textSize="17sp"
        android:textStyle="bold"/>   
</LinearLayout>
  •  Its the time to write the java code, open your MainActivity.java and paste the following code to create a simple ListView. I am puting all the list data in an array called listElements[] and here ArrayAdapter is used to attached the listview.

package com.example.robi;

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 {

    private ListView list;

    ArrayAdapter<String> adapter;

  
    EditText edtSearch;

  
    ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Data to add into listview
        String listElements[] = { "Audi", "Frari", "Fortuner", "Bugatti",
                "Hennessey Venom", "Boster-b1", "Verna", " McLaren F1", "I-20",
                "Hypersport", "Koenigsegg Agera ", "Mercedes-Benz" };

        list = (ListView) findViewById(R.id.list_view);
        edtSearch = (EditText) findViewById(R.id.Search_box);

        // Now Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.mylist,
                R.id.List_item, listElements);
        list.setAdapter(adapter);

        /**
         * below i am Enabling the Search Filter
         * */
        edtSearch.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) {
               
            }
        });
    }

}


How to Enable the Search Functionality 
 We have to add a  addTextChangedListener to EditText.when we enter some thing new to EditText we need to get the text from it and passing it to array adapter filter.  
inputSearch.addTextChangedListener(new TextWatcher() {
     
    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
 
        MainActivity.this.adapter.getFilter().filter(cs);  
    }
     
    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
      
         
    }
     
    @Override
    public void afterTextChanged(Editable arg0) {
                                
    }
});
  •  Adding properties in AndroidManifest.xml file.
android:windowSoftInputMode="stateHidden"
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.robi"
    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="com.example.robi.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>
  •  To run the application, right click on the project -> Run As -> Android Application. You should see following result in your device. 

 Output:        
                             







Please Share this tutorial On:

    

2 comments: