过滤列表视图,自定义适配器不过滤

时间:2015-12-21 13:55:53

标签: android listview android-listview

我想根据我的edittext中输入的内容过滤我的listview,但是listview没有被过滤。希望有人可以帮助我。先感谢您。

这是我的适配器代码:

public class ListofCityAdapter extends ArrayAdapter implements Filterable{
    int groupid;
    ArrayList<City> records;
    ArrayList<City> items;
    Context context;


    public ListofCityAdapter(Context context, int vg, int id, ArrayList<City> objects) {

        super(context, vg, id, objects);
        this.context = context;
        groupid = vg;
        this.records = objects;


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

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

    public long getItemId(int position) {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        View itemView = inflater.inflate(groupid, parent, false);

        TextView textName = (TextView) itemView.findViewById(R.id.city_name);
        textName.setText(records.get(position).getCityName());
        TextView cityregion = (TextView)itemView.findViewById(R.id.city_region);
        cityregion.setText(records.get(position).getRegion());
       ImageView image = (ImageView)itemView.findViewById(R.id.image);
        new DownloadImageTask(image).execute(records.get(position).getImage());
        return itemView;

    }
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }

    }
    public Filter getFilter() {
        return new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<City> results = new ArrayList<City>();
                if (records == null)
                    records = items;
                if (constraint != null) {
                    if (records != null && records.size() > 0) {
                        for (final City g : records) {
                            if (g.getCityName().toLowerCase()
                                    .contains(constraint.toString()))
                                results.add(g);
                        }
                    }
                    oReturn.values = results;
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                items = (ArrayList<City>) results.values;
                notifyDataSetChanged();
            }
        };
    }

    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();

    }
}

这是我的ListofCity.class。这是

public class ListofCity extends Fragment implements  AdapterView.OnItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
    Activity context;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    ProgressDialog pd;
    Spinner filter;
    ListofCityAdapter cityAdapter;
    GridView listCity;
    ArrayList<City> records;
    int id;
    EditText search;
     //  SharedPreferences.Editor citylist;
    String line=null;
    String filtering,cityname;
    SwipeRefreshLayout swipeLayout;
    public ListofCity(){

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_listof_city, container, false);

        context = getActivity();
        records = new ArrayList<City>();
        listCity = (GridView) view.findViewById(R.id.cities);
        cityAdapter = new ListofCityAdapter(context, R.layout.city_layout, R.id.city_name, records);
        listCity.setAdapter(cityAdapter);
        search = (EditText) view.findViewById(R.id.inputSearch);
        filter = (Spinner) view.findViewById(R.id.filter);
        String categories[] = getResources().getStringArray(R.array.filtering);
        ArrayAdapter<String> cat = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);
        cat.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        filter.setAdapter(cat);
       listCity.setTextFilterEnabled(true);
        filter.setOnItemSelectedListener(this);
        swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});

        listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent myIntent = new Intent(view.getContext(), City_attractions.class);
                Toast.makeText(getActivity(), "Opening", Toast.LENGTH_LONG).show();
                cityname = records.get(position).getCityName();
                String info = records.get(position).getDescription();
                String area = records.get(position).getArea();
                String population = records.get(position).getPopulation();
                String region = records.get(position).getRegion();
                String province = records.get(position).getProvince();
                myIntent.putExtra("cityname", cityname);
                myIntent.putExtra("cityinfo", info);
                myIntent.putExtra("cityarea", area);
                myIntent.putExtra("citypopulation", population);
                myIntent.putExtra("cityregion", region);
                myIntent.putExtra("cityprovince", province);
                startActivity(myIntent);
            }
        });

        search.addTextChangedListener(new TextWatcher() {

            @Override

            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

                cityAdapter.getFilter().filter(cs);

            }

            @Override

            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,

                                          int arg3) {

            }

            @Override

            public void afterTextChanged(Editable arg0) {

            }

        });
        return view;

    }




    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        fetchCity fetch = new fetchCity();
        switch (position){
            case 0:
                filtering ="All";
                fetch.execute();
                break;
            case 1:
                filtering ="Alphabetically";
                fetch.execute();
                break;
            case 2:
                filtering ="Region";
                fetch.execute();
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(false);
            }
        }, 5000);
    }


    private class fetchCity extends AsyncTask<Void, Void, Void> {

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        protected void onPreExecute() {
            super.onPreExecute();

            pd = new ProgressDialog(context);
            pd.setTitle("Retrieving data");
            pd.setMessage("Please wait...");
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
        }

        protected Void doInBackground(Void... params) {
            InputStream is = null;
            String result = "";
            nameValuePairs.add(new BasicNameValuePair("filter", filtering));
            try
            {
                records.clear();
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://igph.esy.es/getcity.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("pass 1", "connection success ");
            }
            catch(Exception e)
            {
                Log.e("Fail 1", e.toString());
                Toast.makeText(getActivity(), "Invalid IP Address",
                        Toast.LENGTH_LONG).show();
            }

            try
            {
                BufferedReader reader = new BufferedReader
                        (new InputStreamReader(is,"utf-8"),8);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                Log.e("pass 2", "connection success ");
            }
            catch(Exception e)
            {
                Log.e("Fail 2", e.toString());
            }


            //parse json data
            try {
                Log.i("tagconvertstr", "["+result+"]");
                // Remove unexpected characters that might be added to beginning of the string
                result = result.substring(result.indexOf(""));
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    City p = new City();
                    p.setCityName(json_data.getString("cityName"));
                    p.setArea(json_data.getString("area"));
                    p.setPopulation(json_data.getString("population"));
                    p.setImage(json_data.getString("path"));
                    p.setDescription(json_data.getString("city_info"));
                    p.setProvince(json_data.getString("province"));
                    p.setRegion(json_data.getString("region"));

                    records.add(p);
                }
            } catch (Exception e) {
                Log.e("ERROR", "Error pasting data " + e.toString());

            }

            return null;
        }


        protected void onPostExecute(Void result) {
            if (pd != null) pd.dismiss(); //close dialog
            Log.e("size", records.size() + "");
            cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
        }
    }

}

0 个答案:

没有答案