Recyclerview с нижним колонтитулом, неспособным удалить последний элемент

Я использую recyclerview с нижним колонтитулом все работает нормально. но я не могу удалить последний элемент. Предположим, что теперь у нас есть 2 продукта в списке, если пользователь удалит один продукт, тогда 1 продукт останется в recyclerview, тогда я не смогу удалить этот оставшийся продукт.

Пока у меня есть один элемент, он показывает идентификатор PACK ID

genericViewHolder.removes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        packid=currentItem.getCart_Product_packid();
                        System.out.println("PACK ID"+packid);
                        deletetocart();
                    }
                });

АДАПТЕР

public class HeaderFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private static final int TYPE_HEADER = 0;
        private static final int TYPE_ITEM = 1;
        private static final int TYPE_FOOTER = 2;
        private ArrayList<CartModel> idlistData;
        private AQuery aQuery;

        Context context;

        public HeaderFooterAdapter(Context context,ArrayList<CartModel> idlistData) {
            this.context = context;
            this.idlistData = idlistData;
            aQuery = new AQuery(this.context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
            if(viewType == TYPE_HEADER) {
                View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.item_header, parent, false);
                return new HeaderViewHolder (v);
            } else if(viewType == TYPE_FOOTER) {
                View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.item_footer, parent, false);
                return new FooterViewHolder (v);
            } else if(viewType == TYPE_ITEM) {
                View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.listitem_buynow, parent, false);
                return new GenericViewHolder (v);
            }
            return null;
        }

        private CartModel getItem (int position) {
            return idlistData.get (position);
        }


        @Override
        public void onBindViewHolder (RecyclerView.ViewHolder holder, int position) {
            if(holder instanceof HeaderViewHolder) {
                HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
                headerHolder.txtTitleHeader.setText ("Header");
                headerHolder.txtTitleHeader.setOnClickListener (new View.OnClickListener () {
                    @Override
                    public void onClick (View view) {
                       // Toast.makeText (context, "Clicked Header", Toast.LENGTH_SHORT).show ();
                    }
                });
            } else if(holder instanceof FooterViewHolder) {
                FooterViewHolder footerHolder = (FooterViewHolder) holder;
                footerHolder.txtTitleFooter.setText ("Footer");
                footerHolder.FooterCheckout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                       // Toast.makeText(context, "Clicked Footer", Toast.LENGTH_SHORT).show();
                        if(userd > 0)
                        {
                            System.out.println("Positive");
                            Intent intent=new Intent(BuyNowActivity.this,DelieveringProduct.class);
                            startActivity(intent);
                        }
                        else
                        {
                            System.out.println("Negative");
                            String skipsid=String.valueOf(userd);
                            Intent intent=new Intent(BuyNowActivity.this,Login_Page.class);
                            intent.putExtra("proceedtocheckoutid",skipsid);
                            intent.putExtra("isCheckOut",true);
                            startActivity(intent);
                        }
                    }
                });


            } else if(holder instanceof GenericViewHolder) {
                final CartModel currentItem = getItem (position - 1);
                final GenericViewHolder genericViewHolder = (GenericViewHolder) holder;
                genericViewHolder.txtName.setText(currentItem.getCart_Product_Name());
                String pics = currentItem.getCart_Product_Img();
                aQuery.id(genericViewHolder.proimage).image(pics, true, true, 0, R.mipmap.ic_launcher);

                genericViewHolder.buynowprice.setText("$" + currentItem.getCart_Product_Price());
                genericViewHolder.buynowqtys.setText(currentItem.getCart_Product_Qty());
                genericViewHolder.discounttext.setText(currentItem.getCart_Product_packDiscount());
                subtotal.setText("$" + currentItem.getCart_Product_Price());



                genericViewHolder.edtcoupan.setText(currentItem.getCart_Product_coupancode());

                genericViewHolder.gocoupan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(genericViewHolder.edtcoupan.getText().toString().trim().length() > 0)
                        {

                             couponcode=genericViewHolder.edtcoupan.getText().toString();
                            packid=currentItem.getCart_Product_packid();
                            System.out.println("Coupan Code on click"+couponcode);
                            goforcoupan();
                        }
                    }
                });
                genericViewHolder.removes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        packid=currentItem.getCart_Product_packid();
                        System.out.println("PACK ID"+packid);
                        deletetocart();
                    }
                });

        }
        @Override
        public int getItemViewType (int position) {
            if (isPositionHeader (position)) {
                return TYPE_HEADER;
            } else if(isPositionFooter (position)) {
                return TYPE_FOOTER;
            }
            return TYPE_ITEM;
        }

        private boolean isPositionHeader (int position) {
            return position == 0;
        }

        private boolean isPositionFooter (int position) {
            return position == idlistData.size () + 1;
        }

        @Override
        public int getItemCount () {
            return idlistData.size () + 2;
        }

        class FooterViewHolder extends RecyclerView.ViewHolder {
            Button FooterCheckout;
            TextView txtTitleFooter;
            public FooterViewHolder (View itemView) {
                super (itemView);
                this.txtTitleFooter = (TextView) itemView.findViewById (R.id.txtFooter);
                this.FooterCheckout = (Button) itemView.findViewById (R.id.footercheckout);
            }
        }

        class HeaderViewHolder extends RecyclerView.ViewHolder {
            TextView txtTitleHeader;
            public HeaderViewHolder (View itemView) {
                super (itemView);
                this.txtTitleHeader = (TextView) itemView.findViewById (R.id.txtHeader);
            }
        }

        class GenericViewHolder extends RecyclerView.ViewHolder {
             TextView discounttext;
            LinearLayout lindiscount;
            EditText edtcoupan;
            TextView txtName,buynowprice,buynowqtys,buynowfreq,gocoupan,removes,firsttxt,thirdtxt;
            public ImageView proimage;
            public RelativeLayout linfreq,linqty;
            public GenericViewHolder (View itemView) {
                super (itemView);
                this.txtName = (TextView) itemView.findViewById (R.id.listitem_buynow_title);
                this.proimage = (ImageView)itemView.findViewById(R.id.listitem_buynow_image);
                this.buynowprice = (TextView)itemView.findViewById(R.id.listitem_buynow_price);
                this.buynowqtys = (TextView)itemView.findViewById(R.id.listitem_buynow_qtys);
                this.buynowfreq = (TextView)itemView.findViewById(R.id.listitem_buynow_freq);
                this.gocoupan = (TextView)itemView.findViewById(R.id.listitem_buynow_gocoupan);
                this.edtcoupan = (EditText)itemView.findViewById(R.id.listitem_buynow_coupan);
                this.removes = (TextView)itemView.findViewById(R.id.listitem_buynow_remove);
                this.linfreq = (RelativeLayout)itemView.findViewById(R.id.linfreq);
                this.linqty = (RelativeLayout)itemView.findViewById(R.id.linqty);
                this.lindiscount = (LinearLayout)itemView.findViewById(R.id.coupancodeavailable);
                this.discounttext = (TextView)itemView.findViewById(R.id.listitem_buynow_discountstring);
                this.firsttxt = (TextView)itemView.findViewById(R.id.firsttext);
                this.thirdtxt = (TextView)itemView.findViewById(R.id.thirdtext);
            }
        }
    }

deletetocart

JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, addtocarturl, new JSONObject(params),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        System.out.println("response -->> " + response.toString());
                        cartlist=new ArrayList<CartModel>();

                        try {

                            for (int i = 0; i < response.length(); i++) {

                                JSONObject person = (JSONObject) response
                                        .get(i);

                                System.out.println("person"+person);

                                String responsecode = person.getString("subTotal");
                                System.out.println("subtot"+responsecode);

                                System.out.println("person"+person);


                                if(person.getString("responseCode").equals("1"))
                                {

                                    JSONArray itemslist=person.optJSONArray("itemList");

                                    if(itemslist==null)
                                    {

                                        Toast.makeText(BuyNowActivity.this, "Your Shopping Cart is Empty", Toast.LENGTH_SHORT).show();

                                    }
                                    else {

                                        for (int j = 0; j < itemslist.length(); j++) {

                                            JSONObject cartitems = itemslist.getJSONObject(j);
                                            CartModel cvm = new CartModel();
                                            cvm.setCart_Product_Name(cartitems.getString("prodNarration"));
                                            cvm.setCart_Product_Price(cartitems.getString("finalPrice"));
                                            cvm.setCart_Product_Id(cartitems.getString("productId"));
                                            cvm.setCart_Product_Img(cartitems.getString("packLink"));
                                            cvm.setCart_Product_Qty(cartitems.getString("qty"));
                                            cvm.setCart_Product_packDiscount(cartitems.getString("packDIscDesc"));

                                            cartlist.add(cvm);
                                        }

                                        Toast.makeText(BuyNowActivity.this, "Product Removed Successfully", Toast.LENGTH_SHORT).show();
                                    }
                                }
                                else {
                                    System.out.println("something wrong");
                                }

                                rcAdapter = new HeaderFooterAdapter(BuyNowActivity.this,cartlist);
                                rView.setAdapter(rcAdapter);

                            }

Ответ 1

Это просто предположение, но вы не разбираете свой packId, а повторно инициализируете свой список после удаления одного элемента.

if(person.getString("responseCode").equals("1"))
{

    JSONArray itemslist=person.optJSONArray("itemList");

    if(itemslist==null)
    {

        Toast.makeText(BuyNowActivity.this, "Your Shopping Cart is Empty", Toast.LENGTH_SHORT).show();

    }
    else {

        for (int j = 0; j < itemslist.length(); j++) {

            JSONObject cartitems = itemslist.getJSONObject(j);
            CartModel cvm = new CartModel();
            cvm.setCart_Product_Name(cartitems.getString("prodNarration"));
            cvm.setCart_Product_Price(cartitems.getString("finalPrice"));
            cvm.setCart_Product_Id(cartitems.getString("productId"));
            cvm.setCart_Product_Img(cartitems.getString("packLink"));
            cvm.setCart_Product_Qty(cartitems.getString("qty"));
            cvm.setCart_Product_packDiscount(cartitems.getString("packDIscDesc"));

            // HERE add some code for parsing packId

            cartlist.add(cvm);
        }

        Toast.makeText(BuyNowActivity.this, "Product Removed Successfully", Toast.LENGTH_SHORT).show();
    }
}

Попробуйте добавить код синтаксического анализа, где я добавил комментарий.

Надеюсь, это поможет вам.