简单适配器,过滤时索引无效

时间:2014-10-27 22:40:01

标签: java android listview android-listview hashmap

我正在使用数据库中的数据填充列表视图,它包括图像和文本。所以我实际上无法过滤数据然后将其传递给listview。我必须过滤listview它是自己的。我使用简单的适配器和图像加载填充了listview。问题是当过滤列表视图时它会崩溃。(参见logcat)。

我正在使用的代码:

用于处理图像的自定义简单适配器

public class ExtendedSimpleAdapter extends SimpleAdapter{
    List<HashMap<String, String>> map;
    String[] from;
    int layout;
    int[] to;
    Context context;
    LayoutInflater mInflater;

    public ExtendedSimpleAdapter(Context context, ArrayList<HashMap<String, String>> data,
                                 int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        layout = resource;
        map = data;
        this.from = from;
        this.to = to;
        this.context = context;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return this.createViewFromResource(position, convertView, parent, layout);

    }

    private View createViewFromResource(int position, View convertView,
                                        ViewGroup parent, int resource) {
        View v;
        if (convertView == null) {
            v = mInflater.inflate(resource, parent, false);
        } else {
            v = convertView;
        }

        this.bindView(position, v);

        return v;
    }


    private void bindView(int position, View view) {
        final Map dataSet = map.get(position);
        if (dataSet == null) {
            return;
        }

        final ViewBinder binder = super.getViewBinder();
        final int count = to.length;

        for (int i = 0; i < count; i++) {
            final View v = view.findViewById(to[i]);
            if (v != null) {
                final Object data = dataSet.get(from[i]);
                String text = data == null ? "" : data.toString();
                if (text == null) {
                    text = "";
                }

                boolean bound = false;
                if (binder != null) {
                    bound = binder.setViewValue(v, data, text);
                }

                if (!bound) {
                    if (v instanceof Checkable) {
                        if (data instanceof Boolean) {
                            ((Checkable) v).setChecked((Boolean) data);
                        } else if (v instanceof TextView) {
                            // Note: keep the instanceof TextView check at the bottom of these
                            // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                            setViewText((TextView) v, text);
                        } else {
                            throw new IllegalStateException(v.getClass().getName() +
                                    " should be bound to a Boolean, not a " +
                                    (data == null ? "<unknown type>" : data.getClass()));
                        }
                    } else if (v instanceof TextView) {
                        // Note: keep the instanceof TextView check at the bottom of these
                        // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                        setViewText((TextView) v, text);
                    } else if (v instanceof ImageView) {
                        if (data instanceof Integer) {
                            setViewImage((ImageView) v, (Integer) data);
                        } else if (data instanceof String) {
                            setViewImage((ImageView) v, (String) data);
                        } else {
                            setViewImage((ImageView) v, text);
                        }

                    } else {
                        throw new IllegalStateException(v.getClass().getName() + " is not a " +
                                " view that can be bounds by this SimpleAdapter");
                    }
                }
            }
        }
    }


    @Override
    public int getCount() {
        return super.getCount();
    }

    public void setViewImage(ImageView v, String bmp) {
        v.setImageBitmap(ImageTools.decodeBase64(bmp));
    }

}

调用该课程:

  adapter = new ExtendedSimpleAdapter(
                getActivity(), doctorsList,
                R.layout.listview_item_layout_doctor,
                new String[]{KEY_ID, KEY_NAME, KEY_SPECIALTY, KEY_RATING, KEY_ACCOUNT, KEY_ACTIVE, KEY_IMAGE},

                new int[]{R.id.id, R.id.fname, R.id.Specialty, R.id.Rating, R.id.Account, R.id.Active, R.id.doctorImage});

logcat的:

java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
            at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
            at java.util.ArrayList.get(ArrayList.java:308)
            at my.app.adapters.ExtendedSimpleAdapter.bindView(ExtendedSimpleAdapter.java:61)
            at my.app.adapters.ExtendedSimpleAdapter.createViewFromResource(ExtendedSimpleAdapter.java:54)
            at my.app.adapters.ExtendedSimpleAdapter.getView(ExtendedSimpleAdapter.java:41)

1 个答案:

答案 0 :(得分:0)

我通过实施自定义过滤器修复了它:

   private class CustomFilter extends Filter {

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

            if (mUnfilteredData == null) {
                mUnfilteredData = new ArrayList<HashMap<String, String>>(map);
            }

            if (prefix == null || prefix.length() == 0) {
                List<HashMap<String, String>> list = mUnfilteredData;
                results.values = list;
                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase();

                List<HashMap<String, String>> unfilteredValues = mUnfilteredData;
                int count = unfilteredValues.size();

                ArrayList<Map<String, ?>> newValues = new ArrayList<Map<String, ?>>(count);

                for (int i = 0; i < count; i++) {
                    Map<String, ?> h = unfilteredValues.get(i);
                    if (h != null) {

                        int len = to.length;

                        for (int j=0; j<len; j++) {
                            String str =  (String)h.get(from[j]);

                            String[] words = str.split(" ");
                            int wordCount = words.length;

                            for (int k = 0; k < wordCount; k++) {
                                String word = words[k];

                                if (word.toLowerCase().contains(prefixString)) {
                                    newValues.add(h);
                                    break;
                                }
                            }
                        }
                    }
                }

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

            return results;
        }

        @SuppressWarnings("unchecked")
        protected void publishResults(CharSequence constraint, FilterResults results) {
            //Remove duplicates
            map.addAll((java.util.Collection<? extends HashMap<String, String>>) results.values);
            HashSet hs = new HashSet();
            hs.addAll(map);
            map.clear();
            map.addAll(hs);
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

将此添加到适配器:

  @Override
    public Filter getFilter() {
        if(filter != null) return filter;
        else return filter = new CustomFilter();
    }