Search This Blog

Friday, 26 April 2013

Implementing Search functionality inside Android ListView.

Listing in android contains many features that make ListView a powerful tool. Android developer are very much aware from recycling of View inside BaseAdapter. This tutorial address the issue(or say requirement) of searching inside a ListView.
Concept roam around performing search operation on Array and redraw the ListView.
Let Do this step wise



Step 1) Create one simple User interface to handle requirement search

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <RelativeLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="5dp"
        android:background="@drawable/search_input1" >

        <Button
            android:id="@+id/btnSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="2dp"
            android:background="@drawable/cancel_search" />

        <Button
            android:id="@+id/btnLeft"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="2dp"
            android:background="@drawable/icon_search" />

        <EditText
            android:id="@+id/edSearch"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/btnSearch"
            android:layout_toRightOf="@id/btnLeft"
            android:background="@null"
            android:hint="Search"
            android:imeOptions="actionSearch"
            android:singleLine="true" />
    </RelativeLayout>

    <ListView
        android:id="@+id/mListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/top"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:cacheColorHint="@android:color/transparent"
        android:divider="@android:color/white"
        android:dividerHeight="2dp" >
    </ListView>

</RelativeLayout>

Step 2) Create One BaseAdapter to bind Data inside a ListView

package com.testsearching;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MySimpleSearchAdapter extends BaseAdapter {

    private ArrayList<String> mData = new ArrayList<String>();
    private LayoutInflater mInflater;

    public MySimpleSearchAdapter(Activity activity) {
        mInflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void addItem(String item) {
        mData.add(item);
        notifyDataSetChanged();
    }

    public int getCount() {
        return mData.size();
    }

    public String getItem(int position) {
        return mData.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_one, null);
            holder.textView = (TextView) convertView.findViewById(R.id.text);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String str = mData.get(position);
        holder.textView.setText(str);
        return convertView;
    }

    public class ViewHolder {
        public TextView textView;
    }

}


Step 3) Now write the Search Logic inside your activity

package com.testsearching;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class SearchFunctionality extends Activity implements OnClickListener,
        OnEditorActionListener, OnItemClickListener {
    ListView mListView;
    MySimpleSearchAdapter mAdapter;
    Button btnSearch, btnLeft;
    EditText mtxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mListView = (ListView) findViewById(R.id.mListView);
        mAdapter = new MySimpleSearchAdapter(this);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        btnLeft = (Button) findViewById(R.id.btnLeft);
        mtxt = (EditText) findViewById(R.id.edSearch);
        mtxt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (0 != mtxt.getText().length()) {
                    String spnId = mtxt.getText().toString();
                    setSearchResult(spnId);
                } else {
                    setData();
                }
            }
        });
        btnLeft.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        setData();
    }

    ArrayList<String> mAllData;

    String[] str = { "Hit me Hard", "GIJ, Rise Of Cobra", "Troy",
            "A walk To remember", "DDLJ", "Tom Peter Nmae", "David Miller",
            "Kings Eleven Punjab", "Kolkata Knight Rider", "Rest of Piece" };

    public void setData() {
        mAllData = new ArrayList<String>();
        mAdapter = new MySimpleSearchAdapter(this);
        for (int i = 0; i < str.length; i++) {
            mAdapter.addItem(str[i]);
            mAllData.add(str[i]);
        }
        mListView.setOnItemClickListener(this);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnSearch:
            mtxt.setText("");
            setData();
            break;
        case R.id.btnLeft:

            break;
        }
    }

    public void setSearchResult(String str) {
        mAdapter = new MySimpleSearchAdapter(this);
        for (String temp : mAllData) {
            if (temp.toLowerCase().contains(str.toLowerCase())) {
                mAdapter.addItem(temp);
            }
        }
        mListView.setAdapter(mAdapter);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        return false;
    }

    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
        String str = mAdapter.getItem(position);
        Toast.makeText(this, str, Toast.LENGTH_LONG).show();
    }
}

See Above code output in form of ScreenShot






Download Source Of Application

No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code