简体   繁体   中英

Getter and setter not working as expected in recyclerview android

I am getting json values from volley post request. I am adding those values to list using setter method. When i am retrieving values in adapter onBindViewholder() method and displaying it in a recyclerview result is not getting displayed as expected:

Below code refers to adding values to list from volley request and response in 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:

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:

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:

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:

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 (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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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