1

In my application I have create a custom list view and I want to implement a filter so that the list can be filtered according to the text entered in the EditText. I am using a BaseAdapter as a separate class.

this is my adapter :

public class MyAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
public HashMap<String, String> resultp;

public AllProductAdapter(Context context,
        ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);

}

public int getCount() {
    return data.size();
}

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

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

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

    // Declare Variables
    TextView namaBarang;
    ImageView image;
    TextView harga;
    ImageButton cart;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.listview_viewitem, parent,
            false);
    // Get the position from the results
    resultp = new HashMap<String, String>();
    resultp = data.get(position);

    // Locate the TextViews in listview_item.xml
    namaBarang = (TextView) itemView.findViewById(R.id.judul);
    cart = (ImageButton) itemView.findViewById(R.id.cart);
    harga = (TextView) itemView.findViewById(R.id.posterFile);
    image = (ImageView) itemView.findViewById(R.id.poster);

    // Capture position and set results to the TextViews
    namaBarang.setText(resultp.get(AllProductAgent.TITLE));

    harga.setText(resultp.get(AllProductAgent.HARGA),
            TextView.BufferType.SPANNABLE);

    Spannable spannable = (Spannable) harga.getText();
    spannable.setSpan(new StrikethroughSpan(), 0,
            resultp.get(AllProductAgent.HARGA).length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Capture position and set results to the ImageView
    // Passes flag images URL into ImageLoader.class to download and cache
    // images
    imageLoader
            .DisplayImageList(resultp.get(AllProductAgent.GAMBAR), image);

    // Link to Register Screen
    itemView.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

        }
    });

    // Add ArrayList
    cart.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // Get the position from the results
            HashMap<String, String> resultp = new HashMap<String, String>();
            resultp = data.get(position);

            // show toast if item was been added to cart
            Toast.makeText(
                    context,
                    resultp.get(AllProductAgent.TITLE)
                            + " has been added to Cart", Toast.LENGTH_LONG)
                    .show();

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("nama", resultp.get(AllProductAgent.TITLE));
            map.put("harga", resultp.get(AllProductAgent.HARGA));
            map.put("link_gambar", resultp.get(AllProductAgent.GAMBAR));
            map.put("website", resultp.get(AllProductAgent.WEBSITE));
            BaseActivity.cartList.add(map);

        }
    });
    itemView.setBackgroundColor(position % 2 == 0 ? Color
            .parseColor("#c7eaf8") : Color.parseColor("#FFFFFF"));

    return itemView;
}

how can i filtered my apps? i'm trying so much code and still can't get it.

thanks

zacky
  • 61
  • 1
  • 1
  • 8
  • your list adapter has to implement Filterable interface – pskink Oct 31 '14 at 11:11
  • i know that, but i already try much and i'm still failed to filter my adapter. do you know how? thanks – zacky Oct 31 '14 at 11:52
  • sure, see my answer here : http://stackoverflow.com/questions/19858843/how-to-dynamically-add-suggestions-to-autocompletetextview-with-preserving-chara – pskink Oct 31 '14 at 12:15

2 Answers2

1

Set a TextChangedListener in Searchedittext

Searchtxt.addTextChangedListener(new TextWatcher() {

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

                ListAdapterview.getFilter().filter(s.toString());
            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

Then Implement "Filterable" in Adapter Class

Then Add this code

@SuppressLint("DefaultLocale")
private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final ArrayList<HashMap<String, String>> list = data;

        int count = list.size();
        final ArrayList<HashMap<String, String>> filtereddata = new ArrayList<HashMap<String, String>>();

        String filterableString;

        for (int i = 0; i < count; i++) {
            filterableString = list.get(i).get("ur item name");
            if (filterableString.toString().toLowerCase().contains(filterString)) {
                filtereddata.add(list.get(i));
            }
        }

        results.values = filtereddat;
        results.count = filtereddat.size();

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint,
            FilterResults results) {
        if (results != null) {
            if (results.count > 0) {
                data = new ArrayList<HashMap<String,String>>((ArrayList<HashMap<String, String>>) results.values) ;
            } 

        }
        notifyDataSetChanged();
    }

}
Siva
  • 426
  • 2
  • 8
  • 24
  • hey, i'm still get error.. in ListAdapterview.getFilter().filter(s.toString()); this is my error : The method getFilter() is undefined for the type ListAdapterview. you know why?thanks – zacky Oct 31 '14 at 11:47
  • Change your Baseadapter to ArrayAdapter> – Siva Oct 31 '14 at 12:21
  • public class AllProductAdapter extends ArrayAdapter> implements Filterable. you mean like this? still error :( – zacky Nov 04 '14 at 11:13
0

Assume that you have an EditText with id="field1"

Field1 = (EditText)findViewById(R.id.field1);
Field1.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) {
         /* WORK HERE TO FILTER */
   }
});

Now in the onTextChanged method you can filter your data ( the data must be the ArrayList instance used by the adapter ) in the best way that you can know ( you can use a custom function or a implements a Filter ) and then refresh the adapter to refresh&filter the list.

 public void onTextChanged(CharSequence s, int start, int before, int count) {
     /* WORK HERE TO FILTER */
     doFilter(data);
     MyAdapterInstance.notifyDataSetChanged();
 }
phemt.latd
  • 1,755
  • 20
  • 32
  • doFilter() is the method you must use for a custom filter. If you want to implement your own filter you can create your own function doFilter(). What the function must do depends from you goal! – phemt.latd Oct 31 '14 at 14:07