使用自定义数组适配器在listview中搜索

时间:2015-12-25 13:24:05

标签: android listview android-listview

我目前正在开发一款在线移动应用。我有一个从数据库填充的列表视图。在我的列表视图中,我试图在我的listview上方的edittext中过滤输入数据中的数据。但是我很难在搜索上工作。我使用自定义arrayadapter为我的列表视图,但listview没有被过滤。它显示相同的数据。请那里的任何人帮我解决我的问题。谢谢:))

继承我的ListofCityAdapter.class

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);
   //mage.setImageResource(R.drawable.progress);
    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();

}
}

这是我的ListOfCityPage.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> list;
ArrayList<City> records;
int id;

  //  SharedPreferences.Editor citylist;
String line=null;
String filtering,cityname,text;
SwipeRefreshLayout swipeLayout;
View view;
public ListofCity(){

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    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);
list = new ArrayList<City>();
    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);
        }
    });
    final EditText search = (EditText)view.findViewById(R.id.inputSearch);
    search.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {
            text = search.getText().toString().toLowerCase(Locale.getDefault());
            filter(text);
        }

    });
    return view;

}




public void filter(String charText) {
    charText = text.toLowerCase(Locale.getDefault());
    list.clear();
    if (charText.length() == 0) {
         list.addAll(records);
    } else {
        for (City wp : records) {
            if (wp.getCityName().toLowerCase(Locale.getDefault())
                    .contains(charText)) {
                list.add(wp);
            }
        }
    }
  cityAdapter.notifyDataSetChanged();
}



@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);
            new fetchCity().execute();
        }
    }, 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());
        }

        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
    }
}

}

1 个答案:

答案 0 :(得分:0)

要使用EditText过滤listView,最简单的方法是使用textwatcher。使用textwatcher的 onTextChanged 方法,而不是 afterTextChanged 。我认为您可能也不需要 public void filter(xyz)方法。此代码可能适合您:

function getObjKeys(obj) {
  var keys = [];
  var regex = /"([^:,{}]+)":/g;
  var str = JSON.stringify(obj);
  var m;
  while (m = regex.exec(str)) {
    keys.push(m[1]);
  }
  return keys;
}