Live Search is not working properly in android listview

200 views Asked by At

I am trying to perform search operation on my list view. When I type a character or string which is not present in my list then my code works perfectly (i.e. it shows nothing because no match is found) but, when I enter a name which is present in the list then no matter at what location that name is present my code displays only the first record in the list view. Here is my code for searching operation:

 NameListAdapter = new MyAdapter(this,
                    android.R.layout.simple_list_item_1,NameArrayList
                    );
            lvSearch.setAdapter(NameListAdapter);
            editTextSearch.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                    NameListAdapter.getFilter().filter(cs);
                }
                @Override
                public void beforeTextChanged(CharSequence cs, int arg1, int arg2,
                                              int arg3) {
                }
                @Override
                public void afterTextChanged(Editable cs) {
                }
            });

please help asap.Thank You

2

There are 2 answers

0
Dhiraj Devkar On BEST ANSWER

I solved this problem, rather than using system filter I used my own filter for searching. Following changes are made in my code:

@Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                          int arg3) {

                    String text = edSearch.getText().toString();
                    NameListAdapter.filter(text);
                }

and this filter is method is added:

 // Filter method for search
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        NameArrayList.clear();
        int j;
        if (charText.length() == 0) {
            NameArrayList.addAll(arrayList);
        }
        else
        {
            NameArrayList.clear();
            for (j=0;j<arrayList.size();j++)
            {

           if(arrayList.get(j).toLowerCase(Locale.getDefault()).contains(charText))
                {
                    NameArrayList.add((arrayList.get(j)));
                }
            }
        }
        notifyDataSetChanged();
    }
0
Kamal On

I have done the same without creating such time consuming filter method. NameListAdapter.getFilter().filter(cs); will also work if NameArrayList is type of ArrayAdapter.

Thanks.