使用Searchview过滤器的Recyclerview无效

时间:2017-04-13 12:51:04

标签: android android-recyclerview searchview

我正在使用本教程添加RecyclerView的本地搜索,其中数据来自webservice。问题是当我搜索某些内容时,只显示前两项。当我搜索某些东西时,每次都会发生这种情况。无论我输入什么,只显示前两项。但是当我清除SearchView时,总列表再次显示哪个是正确的。但为什么实际搜索没有过滤正确的项目?

public class ProductsByCategoryActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {

    private RecyclerView recycler;
    private ProductsByCatAdapter adapter;
    private ArrayList<Model> arrayList = new ArrayList<Model>();
    private StaggeredGridLayoutManager gridmanager;

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

        searchview = (SearchView) findViewById(R.id.searchview);

        cd = new ConnectionDetector(ProductsByCategoryActivity.this);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        adapter = new ProductsByCatAdapter(ProductsByCategoryActivity.this, arrayList);
        recycler.setHasFixedSize(true);
        gridmanager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        gridmanager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
        recycler.setLayoutManager(gridmanager);
        recycler.setItemAnimator(null);
        recycler.setAdapter(adapter);

        searchview.setIconifiedByDefault(false);
        searchview.setOnQueryTextListener(this);
        searchview.setSubmitButtonEnabled(true);
        searchview.setQueryHint("Search Here");

        String URL = Utility.PRODBYEVERYTHING;
        prepareData(URL);
    }

    private void prepareData(final String URL) {
        if (arrayList != null) arrayList.clear();

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("sammy_ProductsByCategoryActivity_response " + response);

                        try {
                            JSONObject jObj = new JSONObject(response);
                            if (jObj.getInt("ACK") == 1) {
                                JSONArray jsonArray = jObj.getJSONArray("all_products");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject main = jsonArray.getJSONObject(i);

                                    Model home = new Model();
                                    home.setTitle(main.getString("name"));
                                    home.setImage(main.getString("image"));
                                    home.setPrdid(main.getString("product_id"));
                                    home.setUserid(main.getString("user_id"));

                                    arrayList.add(home);
                                }
                            }

                            adapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            System.out.println("sammy_JSONError " + e);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError) {
                    Toast.makeText(ProductsByCategoryActivity.this, getString(R.string.tooslow), Toast.LENGTH_LONG).show();
                } else if (error instanceof NoConnectionError) {
                    Toast.makeText(ProductsByCategoryActivity.this, getString(R.string.nointernet), Toast.LENGTH_LONG).show();
                } else if (error instanceof AuthFailureError) {
                    System.out.println("sammy_AuthFailureError " + error);
                } else if (error instanceof ServerError) {
                    System.out.println("sammy_ServerError " + error);
                } else if (error instanceof NetworkError) {
                    System.out.println("sammy_NetworkError " + error);
                } else if (error instanceof ParseError) {
                    System.out.println("sammy_ParseError " + error);
                }
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(ProductsByCategoryActivity.this);
        requestQueue.add(stringRequest);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }


    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        adapter.getFilter().filter(newText);
        return true;
    }
}

public class ProductsByCatAdapter extends RecyclerView.Adapter<ProductsByCatAdapter.MyViewHolder> implements Filterable {

    private List<Model> arrayList;
    private List<Model> mFilteredList;
    private Context context;
    private SharedPref pref;

    public ProductsByCatAdapter(Context context, List<Model> arrayList) {
        this.arrayList = arrayList;
        this.mFilteredList = arrayList;
        this.context = context;
        pref = new SharedPref(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {

                String charString = charSequence.toString();

                if (charString.isEmpty()) {
                    mFilteredList = arrayList;
                } else {
                    ArrayList<Model> filteredList = new ArrayList<>();

                    for (Model item : arrayList) {
                        if (item.getTitle().toLowerCase().contains(charString)) {
                            filteredList.add(item);
                        }
                    }

                    mFilteredList = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = mFilteredList;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                mFilteredList = (ArrayList<Model>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        Model model = arrayList.get(position);
        holder.name.setText(model.getTitle());

        if (!TextUtils.isEmpty(model.getImage()))
            Glide.with(context).load(model.getImage()).placeholder(R.drawable.defaultplaceholder).into(holder.image);

    }

    @Override
    public int getItemCount() {
        return mFilteredList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView name;
        ImageView image;
        RelativeLayout relativeLayout;

        MyViewHolder(View view) {
            super(view);
            name = (TextView) view.findViewById(R.id.titletxt);
            image = (ImageView) view.findViewById(R.id.image);
            relativeLayout = (RelativeLayout) view.findViewById(R.id.RL);
            relativeLayout.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.RL:
                    int pos = getAdapterPosition();
                    String prdid = arrayList.get(pos).getPrdid();
                    String userid = arrayList.get(pos).getUserid();
                    System.out.println("sammy_ProductsByCatAdapter_prdid " + prdid);
                    System.out.println("sammy_ProductsByCatAdapter_userid " + userid);
                    if (userid.equals(pref.getString(Utility.USERID))) {
                        Intent intent = new Intent(context, MyProductDetailsActivity.class);
                        intent.putExtra("prdid", prdid);
                        context.startActivity(intent);
                    } else {
                        Intent intent = new Intent(context, OtherProductDetailsActivity.class);
                        intent.putExtra("prdid", prdid);
                        context.startActivity(intent);
                    }
                    break;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:4)

更改

Model model = arrayList.get(position);

Model model = mFilteredList.get(position); 

答案 1 :(得分:0)

我认为你没有在ProductsByCatAdapter类

中使用replace调用filter类
 public ProductsByCatAdapter(Context context, List<Model> arrayList) {
    this.arrayList = arrayList;
    this.mFilteredList = arrayList;
    this.context = context;
    pref = new SharedPref(context);

   // add below line 
    getFilter();
}