prof_jack
prof_jack

Reputation: 2073

how to filter list items while using base adapter in android?

I have been searching a lot about searching items in list view through edit text,and though I found many questions similar to my problem ,but everywhere either cursor adapter is used where filtered result is fetched directly from database or some array list is used.

In my case I have been using couple of arrays to pass text for my list view using base adapter.as I have never done something like this before,I am unable to understand the use of text watcher .

I debugged the code and found that that publish results method is not getting called up, may be that is why list view is unable to get the new values. Do I have to call listviewadaptercontacts class again with the refreshed values in names array inside on text changed method.

Please help.

public class AllContactsActivity extends ListActivity implements
android.view.View.OnClickListener, OnItemClickListener {

    ListView lv;
    ListViewAdapterContacts lva;
    String[] names, phones, ids, types;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);
        LayoutInflater layoutInflater = getLayoutInflater();
        mainLayout.addView(layoutInflater.inflate(R.layout.allcontacts, null));
        mainLayout.addView(layoutInflater.inflate(R.layout.allbuttons, null));
        this.addContentView(mainLayout, params);

        configureBottomMenu();
        getContacts();

        lv = new ListView(getApplicationContext());
        lv = (ListView) findViewById(android.R.id.list);
        lva = new ListViewAdapterContacts(this, names, types, phones, ids); //passing arrays to class
        lv.setAdapter(lva);
        et = (EditText) findViewById(R.id.searchcontact);
        et.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub
                lva.getFilter().filter(s);

                lva.notifyDataSetInvalidated();
                lva.notifyDataSetChanged();
                lv.setAdapter(lva);
            }

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

                // TODO Auto-generated method stub

            }

            public void afterTextChanged(Editable s) {
                // TODO Auto-generated   method stub
            }
        });

        //some code
    }
}

public class ListViewAdapterContacts extends BaseAdapter implements Filterable {

    private ArrayFilter mFilter;
    private ArrayList < String > mOriginalValues;
    private final Object mLock = new Object();
    private List < String > mObjects;
    List list;

    Activity context;
    String[] names;
    String[] types;
    String[] numbers;
    String[] ids;
    public ListViewAdapterContacts(Activity context, String[] names, String[] types, String[] numbers, String[] ids) {
        // TODO Auto-generated constructor stub

        this.context = context;
        this.names = names;
        this.types = types;
        this.numbers = numbers;
        this.ids = ids;
        Object[] array = names;
        list = Arrays.asList(array);
    }



    public int getCount() {
        // TODO Auto-generated method stub 
        if (names == null) {
            return 0;
        } else {
            return names.length;
        }
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public class viewHolder {
        TextView top;
        TextView bottom;
        TextView downside;
        TextView base;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        viewHolder holder;
        if (convertView == null) {

            LayoutInflater inflator = context.getLayoutInflater();
            convertView = inflator.inflate(R.layout.textviewonly, null);

            holder = new viewHolder();
            holder.top = (TextView) convertView.findViewById(R.id.toptext);
            holder.bottom = (TextView) convertView.findViewById(R.id.bottomtext);
            holder.downside = (TextView) convertView.findViewById(R.id.lowest);
            holder.base = (TextView) convertView.findViewById(R.id.baseid);
            convertView.setTag(holder);
        } else {
            holder = (viewHolder) convertView.getTag();
        }
        holder.top.setText(names[position]);
        holder.bottom.setText(types[position]);
        holder.downside.setText(numbers[position]);
        holder.base.setText(ids[position]);
        return convertView;
    }

    public Filter getFilter() {
        // TODO Auto-generated method stub
        if (mFilter == null) {
            mFilter = new ArrayFilter();
        }
        return mFilter;
    }

    private class ArrayFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();

            if (mOriginalValues == null) {
                synchronized(mLock) {
                    //mOriginalValues = new ArrayList<String>(mObjects);

                    mOriginalValues = new ArrayList < String > (list);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                synchronized(mLock) {
                    ArrayList < String > list = new ArrayList < String > (mOriginalValues);
                    results.values = list;
                    results.count = list.size();
                }
            } else {
                String prefixString = prefix.toString().toLowerCase();

                final ArrayList < String > values = mOriginalValues;
                final int count = values.size();

                final ArrayList < String > newValues = new ArrayList < String > (count);

                for (int i = 0; i < count; i++) {
                    final String value = values.get(i);
                    final String valueText = value.toString().toLowerCase();

                    // First match against the whole, non-splitted value
                    if (valueText.startsWith(prefixString)) {
                        newValues.add(value);
                    } else {
                        final String[] words = valueText.split(" ");
                        final int wordCount = words.length;

                        for (int k = 0; k < wordCount; k++) {
                            if (words[k].startsWith(prefixString)) {
                                newValues.add(value);
                                break;
                            }
                        }
                    }
                }

                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            //noinspection unchecked
            mObjects = (List < String > ) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

Upvotes: 1

Views: 5023

Answers (1)

Mohit Verma
Mohit Verma

Reputation: 3025

In this code:

et.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub
        lva.getFilter().filter(s);

        lva.notifyDataSetInvalidated();
        lva.notifyDataSetChanged();
        lv.setAdapter(lva);
    }

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

      // TODO Auto-generated method stub

    }

    public void afterTextChanged(Editable s) {

        // TODO Auto-generated  method stub      
    }
});

In ontextChanged() method only use:

lva.getFilter().filter(s);

Upvotes: 1

Related Questions