Android - Search in Custom ListView Example - ANDROID - Helper

Wednesday, July 13, 2011

Android - Search in Custom ListView Example

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://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEZP27IjOvcSEs94NihD2deFnKhwllSIj7fhSsYhQwlHAfIbyGrnUUJgOXSfLkON-RhJ3mkzbAyZbEqj4YKZPrhpPXoOienTFYu4N2drwkbpEFfi0XR3EYb0LNKpL3blVQtMm7DrPdKkQ/

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJ9YV4JVukSTrulpUsMFseOKhWCx7Yzj59vHuMv3FX8QjY7EzvGjYfqH9Wo8ZkcOmN7ZRGL4TG7FhXYoTKRy42sbFMVdHfTsvkNALFTwxQaZWF15FtdJrRY0OOoGzUkIMrqPvfWsQYO5o/

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinYapYuQwnxpcPvTdxN9Qv3jHIuJwICoV7yzscur4WEz5vYH2kDUDfxNfhMBIs7FZPtbLsKJu6Vw7RN13WRUwDVfFh0jya3TutZ37LiR-dT5t_cZ2QBYvSZXvHJqWM3u_tvSRzpKG7uOw/


37 comments:

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

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

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

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

    ReplyDelete
  4. 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.

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

    ReplyDelete
  6. 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

    ReplyDelete
  7. 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.

    ReplyDelete
  8. 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]);
    }
    }
    }

    ReplyDelete
    Replies
    1. 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)

      Delete
  9. 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)) )

    ReplyDelete
    Replies
    1. 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.

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

      Delete
    3. 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.

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

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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)

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

    ReplyDelete
  14. Hi ownlatte,

    Use INTENT.

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

    ReplyDelete
  15. 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();
    }

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

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

    I tried and still not success. thank you.

    ReplyDelete
  18. 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.

    ReplyDelete
  19. 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. :)

    ReplyDelete
  20. 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"

    ReplyDelete
  21. how to i get contact name and number in android

    ReplyDelete
  22. i gor error: getlayoutinflater();

    create method ;(

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

    ReplyDelete
  24. 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!

    ReplyDelete
  25. 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();
    }
    });

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

    suthar.rajesh2687@gmail.com

    ReplyDelete
  27. Fantastic tutorial. BIG THANKS to you :)

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

    ReplyDelete
  29. Thanks...
    Fantastic tutorial, Very Nice and helpfull :)

    ReplyDelete
  30. But ho to do same with json data coming from server..?

    ReplyDelete
  31. How to search in a custom listview which has spinner and radio button as list items. I want to add search functionality based on spinner values. How to do this.
    Here is the project files.
    https://drive.google.com/open?id=0B3ifR0voltJjRWZJRjZNVEk5UTA

    ReplyDelete
  32. i am getting error in getLayoutInflater();

    ReplyDelete
  33. Can u tell autocomplete search functionality with listview fetch data from json

    ReplyDelete