自定义ListView中的过滤功能无法在android中运行

时间:2016-08-17 09:24:27

标签: android listview adapter android-filterable

我是android的新手并使用自定义适配器处理自定义listView,我有一个listview和edittext,我想使用此添加搜索功能,当用户输入一些字符时,应根据输入过滤listview ,我试过如下,有人可以帮我解决这个问题,

总线适配器

public class BusAdapter extends BaseAdapter implements Filterable{
    public ArrayList<Bus> BusArray;
    private Context mContext;
     // Original Values
    private ArrayList<Bus> mDisplayedValues;


    public BusAdapter(Context paramContext, ArrayList<Bus> BusArray) {
        this.mContext = paramContext;
        this.mDisplayedValues = BusArray;
        this.BusArray = BusArray;

    }

    public int getCount() {
        return this.BusArray.size();
    }

    public Object getItem(int paramInt) {
        return Integer.valueOf(paramInt);
    }

    public long getItemId(int paramInt) {
        return paramInt;
    }

    public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
        LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
        Viewholder localViewholder = null;
        if (paramView == null) {
            paramView = localLayoutInflater.inflate(R.layout.raw_bus, paramViewGroup, false);
            localViewholder = new Viewholder();

            localViewholder.tv_rtname = ((TextView) paramView.findViewById(R.id.tv_rtname));
            localViewholder.tv_from = ((TextView) paramView.findViewById(R.id.tv_from));
            localViewholder.tv_to = ((TextView) paramView.findViewById(R.id.tv_to));
            localViewholder.tv_freq = ((TextView) paramView.findViewById(R.id.tv_fr));


            paramView.setTag(localViewholder);

        } else {

            localViewholder = (Viewholder) paramView.getTag();
        }
        localViewholder.tv_from
                .setText(BusArray.get(paramInt).getRoute_from());
        localViewholder.tv_to
                .setText(BusArray.get(paramInt).getRoute_to());
        localViewholder.tv_rtname
                .setText(BusArray.get(paramInt).getRoute_name());

        return paramView;
    }

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

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

                mDisplayedValues = (ArrayList<Bus>) 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<Bus> FilteredArrList = new ArrayList<Bus>();

                if (BusArray == null) {
                    BusArray = new ArrayList<Bus>(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 = BusArray.size();
                    results.values = BusArray;
                } else {
                    constraint = constraint.toString().toLowerCase();
                    for (int i = 0; i < BusArray.size(); i++) {
                        String data = BusArray.get(i).getRoute_name();
                        if (data.toLowerCase().startsWith(constraint.toString())) {
                            FilteredArrList.add(new Bus(BusArray.get(i).route_id,BusArray.get(i).route_name,BusArray.get(i).route_details,BusArray.get(i).route_from,BusArray.get(i).route_to));
                        }
                    }
                    // set the Filtered result to return
                    results.count = FilteredArrList.size();
                    results.values = FilteredArrList;
                }
                return results;
            }
        };
        return filter;
    }
//get filter



    //end

    static class Viewholder {
        TextView tv_from;
        TextView tv_to;
        TextView tv_rtname;
        TextView tv_freq;

    }

}

活动

public class BusTimingActivity extends AppCompatActivity {
    ListView lv_bus;
    ArrayList<Bus> busList;
    ProgressDialog pDialog;
    InputStream inputStream = null;
    String result;
    BusAdapter adapter;

    EditText et_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_bus_timings);
        lv_bus = (ListView)findViewById(R.id.lv_bus);
        et_search = (EditText)findViewById(R.id.et_search);
        busList = new ArrayList<>();

        et_search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                adapter.getFilter().filter(cs.toString());

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });
        new GETBUSROUTES().execute();

    }
//GET ALL BUS ROUTES..
public class GETBUSROUTES extends AsyncTask<Void, Void, Void> {

    StringEntity se;
    String url;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        busList.clear();
        pDialog = new ProgressDialog(BusTimingActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
        busList.clear();

    }

    @Override
    protected Void doInBackground(Void... params) {
        url = Const.API_URL;

        HttpClient httpClient = new DefaultHttpClient();


        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> valueparams = new ArrayList<NameValuePair>();
        valueparams.add(new BasicNameValuePair("form_type", "all_bus_routes"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(valueparams));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String json = "";

        //getting string entity to http..!!!

        try {

            HttpResponse httpResponse = httpClient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();
            if (inputStream != null) {
                BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    total.append(line).append('\n');
                }
                result = total.toString();
                try {
                    JSONArray results = new JSONArray(result);
                    for (int i = 0; i<results.length() ; i++) {
                        JSONObject c = results.getJSONObject(i);
                        Bus bus = new Bus();
                        bus.setRoute_id(c.getString("route_id"));
                        bus.setRoute_details(c.getString("route_details"));
                        bus.setRoute_from(c.getString("route_from"));
                        bus.setRoute_to(c.getString("route_to"));
                        bus.setRoute_name(c.getString("route_name"));
                        busList.add(bus);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("====RESPONSE FOR BUSES====>" + result.toString());
            } else
                result = "Did not work!";

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // execute HTTP post request

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        //
        if(busList.size()>0){
            adapter = new BusAdapter(BusTimingActivity.this,busList);
            lv_bus.setAdapter(adapter);
            adapter.notifyDataSetChanged();

        }else{
            Toast.makeText(BusTimingActivity.this,"No Routes Found",Toast.LENGTH_SHORT).show();
        }

    }

}

Bus.java

public class Bus {
    public String route_id;
    public String route_name;

    public Bus(String route_id, String route_name, String route_details, String route_from, String route_to) {
        this.route_id = route_id;
        this.route_name = route_name;
        this.route_details = route_details;
        this.route_from = route_from;
        this.route_to = route_to;
    }

    public Bus() {
    }

    public String route_details;

    public String getRoute_from() {
        return route_from;
    }

    public void setRoute_from(String route_from) {
        this.route_from = route_from;
    }

    public String getRoute_id() {
        return route_id;
    }

    public void setRoute_id(String route_id) {
        this.route_id = route_id;
    }

    public String getRoute_name() {
        return route_name;
    }

    public void setRoute_name(String route_name) {
        this.route_name = route_name;
    }

    public String getRoute_details() {
        return route_details;
    }

    public void setRoute_details(String route_details) {
        this.route_details = route_details;
    }

    public String getRoute_to() {
        return route_to;
    }

    public void setRoute_to(String route_to) {
        this.route_to = route_to;
    }

    public String route_from;
    public String route_to;

}

1 个答案:

答案 0 :(得分:0)

由于您似乎只是对getRoute_name()进行过滤,因此可能更容易扩展ArrayAdapter<Bus>,它将为您进行过滤,然后覆盖Bus对象的toString()以返回路由名称。

我不认为这是您的过滤问题,但getItem()应该从您的数组列表中返回一个Bus对象,而不是整数。

正如@Daniel Wilson所指出的那样,你的代码有点困难,因为你的变量以capial字母开头,它使它看起来像一个静态的方法调用。