我在购物车中单个商品的总价格错误。如果我增加数量并减少数量,则会发生以下情况:
增加数量1 = 4,10; 2 = 4,10; 3 = 8,20; 4 = 12,30;减少数量:从4(16,30)减少到3 = 16,40; 2 = 12,30; 1 = 8,20;
但是所有物品的总价是正确的。
public class CartAdapter extends RecyclerView.Adapter<CartViewHolder> {
private List<Order> listData = new ArrayList<>();
private Cart cart;
public CartAdapter(List<Order> listData, Cart cart) {
this.listData = listData;
this.cart = cart;
}
@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(cart);
View itemView = inflater.inflate(R.layout.cart_layout, parent, false);
return new CartViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull final CartViewHolder holder, final int position) {
holder.btn_quantity.setNumber(listData.get(position).getQuantity());
holder.btn_quantity.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
@Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
Locale locale = new Locale("de", "DE");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
double price = (Double.parseDouble(listData.get(position).getPrice()))*(Double.parseDouble(listData.get(position).getQuantity()));
//int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));
holder.txt_price.setText(fmt.format(price));
holder.txt_cart_name.setText(listData.get(position).getProductName());
Order order = listData.get(position);
order.setQuantity(String.valueOf(newValue));
new Database(cart).updateCart(order);
double total = 0;
List<Order> orders = new Database(cart).getCarts();
for (Order item:orders)
total+=(Double.parseDouble(order.getPrice()))*(Integer.parseInt(item.getQuantity()));
cart.txtTotalPrice.setText(fmt.format(total));
}
});
Locale locale = new Locale("de", "DE");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
double price = (Double.parseDouble(listData.get(position).getPrice()))*(Double.parseDouble(listData.get(position).getQuantity()));
//int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));
holder.txt_price.setText(fmt.format(price));
holder.txt_cart_name.setText(listData.get(position).getProductName());
}
@Override
public int getItemCount() {
return listData.size();
}
答案 0 :(得分:0)
问题可能出在代码序列中,您应该输入以下代码:
Order order = listData.get(position);
order.setQuantity(String.valueOf(newValue));
new Database(cart).updateCart(order);
开头:
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
// event listener code
}
这个方块。
我希望它会有所帮助:)