• RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
Posted by Jack - - 33 comments

SEARCH IN CUSTOM LISTVIEW

SOURCE CODE [main.xml] is

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

android:orientation="vertical"
android:layout_width="fill_parent"
                android:layout_height="fill_parent">

                <EditText android:id="@+id/EditText01"
android:layout_height="wrap_content"
                                android:layout_width="fill_parent"
android:hint="Search">                               
                </EditText>

                <ListView android:id="@+id/ListView01"
android:layout_height="wrap_content"
                                android:layout_width="fill_parent">
</ListView>

</LinearLayout>

SOURCE CODE [listview.xml] is

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_height="wrap_content"
android:gravity="left|center"
                android:layout_width="fill_parent"
android:paddingBottom="5px"
                android:background="#fff200"
                android:paddingTop="5px"
android:paddingLeft="5px">

                <ImageView android:id="@+id/ImageView01"
                                android:layout_width="wrap_content"
android:layout_height="wrap_content">
                </ImageView>

                <TextView android:id="@+id/TextView01"
                                android:layout_width="wrap_content"
android:layout_height="wrap_content"
                                android:textSize="20px"
                                android:textStyle="bold"
                                android:layout_marginLeft="10px"
android:textColor="#0099CC">
                </TextView>

</LinearLayout>
   
SOURCE CODE [CustomListViewSearch.java] is

package com.CustomListViewSearch;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class CustomListViewSearch extends Activity
{
EditText edittext;
ListView listview;

String[] text = { "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten" };

int[] image = { R.drawable.one, R.drawable.two, R.drawable.three,
R.drawable.four, R.drawable.five, R.drawable.six, R.drawable.seven,
R.drawable.eight, R.drawable.nine, R.drawable.ten };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();

public void onCreate(Bundle savedInstanceState)
{

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

edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
edittext.addTextChangedListener(new TextWatcher()
{

public void afterTextChanged(Editable s)
{

}

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

}

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

textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();

for (int i = 0; i < text.length; i++)
{
if (textlength <= text[i].length())
{
if (edittext.getText().toString().
equalsIgnoreCase((String) text[i].subSequence(0, textlength)))
{
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}

listview.setAdapter(new MyCustomAdapter
(text_sort, image_sort));

}
});
}

class MyCustomAdapter extends BaseAdapter
{

String[] data_text;
int[] data_image;

MyCustomAdapter()
{

}

MyCustomAdapter(String[] text, int[] image)
{
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Integer> image)
{
data_text = new String[text.size()];
data_image = new int[image.size()];

for(int i=0;i<text.size();i++)
{
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}

}

public int getCount()
{
return data_text.length;
}

public String getItem(int position)
{
return null;
}

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

public View getView(int position, View convertView, ViewGroup parent)
{

LayoutInflater inflater = getLayoutInflater();
View row;

row = inflater.inflate(R.layout.listview, parent, false);

TextView textview = (TextView) row.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) row
.findViewById(R.id.ImageView01);

textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);

return (row);

}
}

}

The OUTPUT will be


https://lh3.googleusercontent.com/-t61mePD9obg/Th1lp2RWmNI/AAAAAAAAALc/6iviMDB_27I/custom_listview_search1.png

https://lh5.googleusercontent.com/-0H2RUBsLIYQ/Th1lqLCn5iI/AAAAAAAAALg/QZe8a5-PYu0/custom_listview_search2.png

https://lh5.googleusercontent.com/-u3ZUYpucy98/Th1lqNyXzsI/AAAAAAAAALk/Uwfq1OYP-yk/custom_listview_search3.png


33 Responses so far.

  1. How to get the running tasks in listview
    thanks in advance

  2. Ken says:

    how can i search inside like if i type "ne" and not "one".

  3. Jack says:

    I couldn't get what you are trying to say.

    Do you need to search the element ONE by typing NE instead of ONE.?

  4. Ken says:

    I mean i tried to type "ne" on seachbox but "One" does not come out of the list. unless I type the first letter "O" then the list shows.

  5. praveen says:

    i have got all the data stored in listview properly.afterthat i want to search .how to do that

  6. taufik says:

    Nice tutorial, can you give an example that tle list act as menus and a click on item wil open a sub menu?

    Thanks in advance

  7. Carontes says:

    What if I would a second "String" instead the "int". Is it possible to make the same thing? The "Search box" will work as now? How should I change the code? Thank you.

  8. Jack says:

    Hi all.

    I was not able to answer your comments. Sorry all..

    Ken - use indexOf() method.

    change this function..

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

    textlength = edittext.getText().length();
    text_sort.clear();
    image_sort.clear();

    for (int i = 0; i < text.length; i++)
    {
    if (textlength <= text[i].length())
    {
    if (text[i].indexOf(edittext.getText().toString()) != -1)
    {
    text_sort.add(text[i]);
    image_sort.add(image[i]);
    }
    }
    }

  9. Jack says:

    Carontes --

    if you have two string arrays and you need to search any one string array then

    use this code

    if (edittext.getText().toString().
    equalsIgnoreCase((String) text1[i].subSequence(0, textlength)) || edittext.getText().toString().
    equalsIgnoreCase((String) text2[i].subSequence(0, textlength)) )

  10. Carontes says:

    Thank you for your answer. When I try to type the first letter into the search box the app crash. The logcat gives me the NullPointerException at these lines:

    listview.setAdapter(new MyCustomAdapter(text_sort,image_sort));

    data_text[i] = text.get(i);


    All I did with your code was only to change int[] with String[] and EditText with AutoCompleteTextView. How can I solve this problem? Thank you.

  11. Carontes says:

    Sorry, I resolved my problem. I made a mistake with my code. Thank you again for your advice.

  12. Carontes says:

    Sorry to bother you again but the app crash when I delete the first letter from the search box. For example if I wrote "Man" when I try to delete "M" the app crash and the logcat gives me
    java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    at this line:
    image_sort.add(image[i]);

    I tried with your original code without add the advice you gave me.

  13. Carontes says:

    How can I search a word without the case sensitive? I tried in this way but under .indexOf appears a red line.

    if (text[i].indexOf(edittext.getText().toString()equalsIgnoreCase((String) text[i].subSequence(0, textlength)) != -1)

  14. shine says:

    Hi~! Nice tutorial. I'm new in android and listview. How can I add section headers?

  15. Arun's says:

    Hi
    its a nice tutorial.
    i am trying to search the whole device like my phone. how can we do it? QSB i tried but not of much help,can you please help

  16. Hi Carontes, to search within a String and without case sensitive..
    replace your:

    if (text[i].indexOf(edittext.getText().toString()equalsIgnoreCase((String) text[i].subSequence(0, textlength)) != -1)

    with:

    if(text[i].toLowerCase().indexOf(edittext.getText().toString().toLowerCase()) != -1)

  17. ownlatte says:

    how to get the list is clicked and go to the next class?

  18. Jack says:

    Hi ownlatte,

    Use INTENT.

    Intent i = new Intent(YourCurrentClass.this, NextClass.class);
    startActivity(i);

  19. ownlatte says:

    and how about when using a condition such as if-else, I use this there is nothing wrong but I can't go to the next class.

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView arg0, View v, int arg2, long arg3) {

    String item = ((TextView)edittext).getText().toString();
    select(item);

    }

    private void select(String item) {

    try {
    Intent i = null;
    if (item.equals("sunday")) {
    startActivity(new Intent(ListviewActivity.this, sunday.class));
    }else if (item.equals("monday")) {
    startActivity(new Intent(ListviewActivity.this, monday.class));
    }
    startActivity(i);
    } catch (Exception e) {
    e.printStackTrace();
    }

  20. Vidya says:

    Hi awesome tutorial... i wanted to know same function on custom cursor adapter... pls post it

  21. please tell me, how to implements this from data SQLite and not from an array.

    I tried and still not success. thank you.

  22. Hi,

    I have three columns viz company code,fname,lname...i want to search the list on all the three..like the user is free to enter anything in the search box and it will fetch all the particular records...

    Please tell me how to implement the same.

    I tried doing it using elseif loop but the application crashes as the company code has a fixed length of 4 but fname and lname varies..

    Please can anyone help me with this.

  23. Hi There Sir. Can you make a tutorial of a custom search for datas native to the phone or memory card. For example, a listview search of contacts or messages, pictures or music files. Any one of those will do thanks. :)

  24. Hi,
    When i use your code it is asking about a method getLayoutInflater() to create.
    it is showing message like below:
    "The method getLayoutInflater() is undefined for the type DoctorsInfoAdapter"

  25. how to i get contact name and number in android

  26. i gor error: getlayoutinflater();

    create method ;(

  27. is der any criteria to adding loading progresbar while searching the items from adapter ???

  28. OMG!!! Thank you so much for this tutorial. It works amazingly! I've spent the whole day looking for something like this, and you have made it as simple as possible! Great work, thanks so much for uploading!

  29. Use This for given example

    listview = (ListView) findViewById(R.id.ListView01);
    listview.setTextFilterEnabled(true);
    listview.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView a, View v, int position,
    long id) {
    Toast.makeText(getApplicationContext(),
    Integer.toString(position), Toast.LENGTH_SHORT).show();
    LinearLayout textView = (LinearLayout) listview
    .getChildAt(position);
    TextView tx = (TextView) textView.getChildAt(1);
    String selectedValue = tx.getText().toString();
    Toast.makeText(getApplicationContext(), selectedValue,
    Toast.LENGTH_SHORT).show();
    }
    });

  30. can you please send me the zip of this program,

    suthar.rajesh2687@gmail.com

  31. Fantastic tutorial. BIG THANKS to you :)

  32. Nice and helpfull this tutorial...
    How to get search item from database

Leave a Reply