简体   繁体   English

getter和setter在recyclerview android中无法按预期工作

[英]Getter and setter not working as expected in recyclerview android

I am getting json values from volley post request. 我从齐射请求中获取json值。 I am adding those values to list using setter method. 我使用setter方法将这些值添加到列表中。 When i am retrieving values in adapter onBindViewholder() method and displaying it in a recyclerview result is not getting displayed as expected: 当我在适配器onBindViewholder()方法中检索值并将其显示在recyclerview结果中时,未按预期显示:

Below code refers to adding values to list from volley request and response in MainActivity.java: 下面的代码引用了在MainActivity.java中向齐射请求和响应中的列表添加值:

    private ProductsPojo pojo;
    public static ProductsAdapter productsAdapter;
    private List<ProductsPojo> pojoList;

    pojo = new ProductsPojo();
    pojoList = new ArrayList<>();

StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
//            Log.d("Appet8","Products response:"+response.toString());

                try {
                   JSONObject jsonObject = new JSONObject(response);
                   JSONArray products = jsonObject.getJSONArray("products");

                   for (int i=0;i<products.length();i++) {
                       JSONObject product_object = products.getJSONObject(i);
                       String name = product_object.getString("name");
                       String price = product_object.getString("price");
                       String product_id = product_object.getString("id");
                       String sessionname = product_object.getString("sessionname");
                       String image = product_object.getString("image");
                       String categoryname = product_object.getString("categoryname");

                       pojo.setName(product_object.getString("name"));
                       pojo.setImage(product_object.getString("image"));
                       pojoList.add(pojo);

                   }
                    productsAdapter = new ProductsAdapter(pojoList,getApplicationContext());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("customer_id", customer_id);
                return params;
            }
        };

        AppController.getInstance().addToRequestQueue(request,tag_request);

Below code refers to setting adapter to recyclerview in a ProductFragment.java: 下面的代码指的是在ProductFragment.java中将适配器设置为recyclerview:

private GridLayoutManager layoutManager;
private RecyclerView recyclerView;

 recyclerView = (RecyclerView) view.findViewById(R.id.productList);
    recyclerView.setHasFixedSize(true);
    layoutManager = new GridLayoutManager(getActivity().getApplicationContext(),3);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(MainActivity.productsAdapter);

Below code refers to adapter class which displays values, ProductsAdapter.java: 下面的代码引用显示值的适配器类ProductsAdapter.java:

public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductsViewHolder> {

    private List<ProductsPojo> productList;
    private Context context;

    public ProductsAdapter(List<ProductsPojo> productList,Context context) {
        this.productList=productList;
        this.context = context;
    }

    @Override
    public ProductsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.
                from(parent.getContext()).
                inflate(R.layout.products_list, parent, false);
        ProductsViewHolder holder = new ProductsViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(final ProductsViewHolder holder,final int position) {

        final ProductsPojo pojo = productList.get(position);
        Log.d("Appet8","Name:"+pojo.getName());

        holder.vTitle.setText(pojo.getName());

        holder.vTitle.setTypeface(MainActivity.font);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               pojo.setSelected(!pojo.isSelected());
               holder.itemView.setBackgroundColor(pojo.isSelected() ? Color.parseColor("#4D79CF08") : Color.parseColor("#2D6F6F6F"));

               if(pojo.isSelected()) {
                holder.selected.setVisibility(View.VISIBLE);
               } else if(!pojo.isSelected()) {
                holder.selected.setVisibility(View.GONE);
               }
            }
        });
     }

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

    public static class ProductsViewHolder extends RecyclerView.ViewHolder {

        protected TextView vTitle;
        protected ImageView image,selected;
        protected CardView product_card;

        public ProductsViewHolder(View v) {
            super(v);
            vTitle = (TextView) v.findViewById(R.id.title);
            image = (ImageView) v.findViewById(R.id.product);
            product_card = (CardView) v.findViewById(R.id.product_card);
            selected = (ImageView) v.findViewById(R.id.selected);
        }
    }

}

This is the response that i get from volley request: 这是我从截击请求中得到的响应:

{
"products":[
        {
            "name":"Idli",
            "price":"120",
            "id":"Fi2mYuQA",
            "sessionname":"Breakfast",
            "image":"VCYwmSae2BShoshone_Falls-1200px.jpeg",
            "categoryname":"Veg"
        },
        {
            "name":"Meals123",
            "price":"200",
            "id":"bmF8Is1Y",
            "sessionname":"Dinner",
            "image":"sIe8JBFzaRstock-photo-115193575.jpg",
            "categoryname":"Non Veg"
        },
        {
            "name":"Dosa",
            "price":"100",
            "id":"e9sWHV4A",
            "sessionname":"Breakfast",
            "image":"j8nu4GpVa7Shoshone_Falls-1200px.jpeg",
            "categoryname":"Veg"
        },
        {
            "name":"Coca",
            "price":"40",
            "id":"0oJDfdCz",
            "sessionname":"Cold Drinks",
            "image":"LrkS8QpAs7Shoshone_Falls-1200px.jpeg",
            "categoryname":"Veg"
        },
        {
            "name":"ICe",
            "price":"100",
            "id":"2ykEgtSs",
            "sessionname":null,
            "image":"KtPX9C26oRShoshone_Falls-1200px.jpeg",
            "categoryname":"Veg"
        }
    ]
}

这是我得到的输出。项目名称重复。

This is the output i am getting. 这是我得到的输出。 Item names are repeated. 项目名称重复。

Below code Refers to ProductsPojo.java: 下面的代码引用ProductsPojo.java:

public class ProductsPojo {
    public String name;
    public String image;
    private boolean isSelected = false;

    public void setName(String name) {
        this.name = name;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public String getImage() {
        return image;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }


    public boolean isSelected() {
        return isSelected;
    }
}

Looks to me like you only ever create one ProductsPojo instance, here: 在我看来,您只能在这里创建一个ProductsPojo实例:

pojo = new ProductsPojo();

And then in your loop you keep modifying this one instance, and then adding it to the list again and again. 然后在循环中,您继续修改此实例,然后一次又一次地将其添加到列表中。 This way you'd end up with the same item (the last one) in your list as many times as the number of objects you got in the response. 这样,您最终得到的列表中的同一项目(最后一项)是响应中得到的对象数量的多少倍。

What you wanted to do was probably to create a new ProductsPojo at the beginning of the for loop every time instead, like this: 您想要做的可能是每次都在for循环的开头创建一个新的ProductsPojo ,如下所示:

for (int i=0;i<products.length();i++) {
    ProductsPojo pojo = new ProductsPojo();

    JSONObject product_object = products.getJSONObject(i);
    String name = product_object.getString("name");
    String price = product_object.getString("price");
    String product_id = product_object.getString("id");
    String sessionname = product_object.getString("sessionname");
    String image = product_object.getString("image");
    String categoryname = product_object.getString("categoryname");

    pojo.setName(product_object.getString("name"));
    pojo.setImage(product_object.getString("image"));
    pojoList.add(pojo);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM