使用自定义数组适配器在列表视图中搜索

问题描述 投票:1回答:2

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

这里是我的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
    }
}

}

android listview android-listview
2个回答
0
投票

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

inputText.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) {
            YouActivityName.this.cityAdapter.getFilter().filter(s);
            cityAdapter.notifyDataSetChanged();

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

0
投票

当您使用简单的listView时

适配器:

public class Adapter extends ArrayAdapter {
    ArrayList<String> list = new ArrayList<>();
    ArrayList<String> filteredData = new ArrayList<>();

    public Adapter(@NonNull Context context, int resource) {
        super(context, resource);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        LayoutInflater inflate = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        @SuppressLint("ViewHolder") View vi = inflate.inflate(R.layout.ly_items, null);
        try {
            JSONObject js = new JSONObject(list.get(position));
            TextView txtItem = vi.findViewById(R.id.txtItem);
            ImageView imgItem = vi.findViewById(R.id.imgItem);
            txtItem.setText(js.getString("name") + " - " + js.getInt("number"));
            Picasso.get().load(js.getString("logo_url")).into(imgItem);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return vi;
    }

    @Override
    public void add(@Nullable Object object) {
        super.add(object);
        list.add(object.toString());
        filteredData.add(object.toString());
    }

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

    @Nullable
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }


    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        list.clear();
        if (charText.length() == 0) {
            list.addAll(filteredData);
        } else {
            for (String wp : filteredData) {

                try {
                    JSONObject json = new JSONObject(wp);
                    if (json.getString("name").toLowerCase().contains(charText) || json.getString("number").contains(charText)) {
                        list.add(wp);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        notifyDataSetChanged();
    }
}

和您的班级:

Adapter adapter;
ListView list;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

list = findViewById(R.id.list);

edtSearch = findViewById(R.id.edtSearch);

    adapter = new Adapter(this, android.R.layout.simple_list_item_1);
    EditText edtSearch;

list.setAdapter(adapter);

edtSearch.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) {
                adapter.filter(s.toString());
            }

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

    }
© www.soinside.com 2019 - 2024. All rights reserved.