Filter on listview disappear listitems while entering something into edittext

1.4k views Asked by At

I am suffering a weird problem. Actually I have a customize listview in which I am using a filter, everything working fine but when I am typing a text to edittext it disappear the all listitem. I am strange why this going on with me, still I am not a champ of android so need some help. I have seen many similar problems on stackoverflow like this,this,this, and many more, but nothing works in my case. I dont know where i am doing mistake.

My listitem click working fine, So hope it will also work after item search into edittext.

Here is my MainActivity.java :

package com.sunil.listviewmuntilerowdelete;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;



    public class MainActivity extends Activity {

        private String[] myfriendname = null;
        EditText edtSearch;
        private int[] photo = null;
        ListView listView = null;
        Context contex = null;
        MyListAdapter adapter = null;
        private List<MyFriendsSDetails> list = new ArrayList<MyFriendsSDetails>();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            contex = this;
            listView = (ListView) findViewById(R.id.listview);
            edtSearch = (EditText) findViewById(R.id.EditText01);
            myfriendname = new String[] { "Sunil Gupta", "Abhishek Tripathi",
                    "Sandeep Pal", "Amit Verma" };

            photo = new int[] { R.drawable.sunil, R.drawable.abhi,
                    R.drawable.sandy, R.drawable.amit };

            final String text[] = { "Sunil is a great man",
                    "Abhishek is hardworking", "Sandeep is same as amit",
                    "Amit is unique" };

            final Integer[] image = { R.drawable.sunil, R.drawable.abhi,
                    R.drawable.sandy, R.drawable.amit,

            };

            for (int index = 0; index < myfriendname.length; index++) {
                MyFriendsSDetails details = new MyFriendsSDetails(
                        myfriendname[index], photo[index]);
                list.add(details);
            }

            adapter = new MyListAdapter(contex, list);
            listView.setAdapter(adapter);
            listView.setTextFilterEnabled(true);
            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 s) {
                    // TODO Auto-generated method stub

                }
            });

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    Intent intent = new Intent(MainActivity.this,
                            SecondActivity.class);

                    intent.putExtra("key1", image[position]);
                    intent.putExtra("key2", text[position]);
                    startActivity(intent);

                }
            });

        }
    }

MyListAdapter.java

    package com.sunil.listviewmuntilerowdelete;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyListAdapter extends ArrayAdapter<MyFriendsSDetails> {

    Context context;
    LayoutInflater inflater;
    List<MyFriendsSDetails> list;

    public MyListAdapter(Context context, List<MyFriendsSDetails> list) {
        super(context, 0, list);

        this.context = context;
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

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

        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.list_item, null);
            holder.name = (TextView) convertView.findViewById(R.id.title);

            holder.photo = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.name.setText(list.get(position).getMyfriendname());

        holder.photo.setImageResource(list.get(position).getPhoto());
        return convertView;
    }

    private class ViewHolder {
        TextView name;

        ImageView photo;
    }
}

Here is MyFriendsSDetails.java :

    package com.sunil.listviewmuntilerowdelete;

public class MyFriendsSDetails {

    private String myfriendname = null;

    private int photo = 0;

    public MyFriendsSDetails(String friendname, int myphoto) {
        this.myfriendname = friendname;

        this.photo = myphoto;
    }

    public String getMyfriendname() {
        return myfriendname;
    }

    public void setMyfriendname(String myfriendname) {
        this.myfriendname = myfriendname;
    }

    public int getPhoto() {
        return photo;
    }

    public void setPhoto(int photo) {
        this.photo = photo;
    }

}

Thanks in advance.

1

There are 1 answers

0
Karan On

As you are using custom adapter, android cant recognize "MainActivity.this.adapter.getFilter().filter(cs);"

You have to override getFilter() method and do manual changes.

Checkout below code :

 @Override
public Filter getFilter() {
    Filter filter = new Filter() {

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {


            mDisplayedValues = (ArrayList<HashMap<String, String>>) results.values; // has the filtered values
            notifyDataSetChanged();  // notifies the data with new filtered values
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();        // Holds the results of a filtering operation in values
            ArrayList<HashMap<String, String>> FilteredArrList = new ArrayList<HashMap<String, String>>();

            if (mOriginalValues == null) {
                mOriginalValues = new ArrayList<HashMap<String, String>>(mDisplayedValues); // saves the original data in mOriginalValues

            }

            /********
             * 
             *  If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
             *  else does the Filtering and returns FilteredArrList(Filtered)  
             *
             ********/
            if (constraint == null || constraint.length() == 0) {

                // set the Original result to return  
                results.count = mOriginalValues.size();
                results.values = mOriginalValues;
            } else {
                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mOriginalValues.size(); i++) {

                    String data = mOriginalValues.get(i).get("name");

                    if (data.toLowerCase().startsWith(constraint.toString())) {
                        HashMap<String, String> hmap=new HashMap<String, String>();
                        hmap.put("name", mOriginalValues.get(i).get("name"));
                        hmap.put("image", mOriginalValues.get(i).get("image"));
                        FilteredArrList.add(hmap);
                        Log.e("DEBUG", "name : "+data);
                    }
                }
                // set the Filtered result to return
                results.count = FilteredArrList.size();
                results.values = FilteredArrList;
            }
            return results;
        }
    };
    return filter;
}

and use it in your adapter getView()

 holder.name.setText(mDisplayedValues.get(position).get("name"));