【问题标题】:Calculating the total amount in the cart?计算购物车中的总金额?
【发布时间】:2020-03-23 04:31:15
【问题描述】:

我无法在 RecylerView 的项目列表中获得总价。我从 firestore 获得了价格并乘以数量,但是如何获得 recylerView 中添加项目的总价格。我的问题是没有计算项目的总成本。 谢谢! 我的代码:

 public class ItemCartRecyelerAdapter extends FirestoreAdapter<ItemCartRecyelerAdapter.ViewHolder>{

private static final String TAG = "ItemRecyelerAdapter";



public interface OnItemSelectedListener {
    void OnItemSelected(DocumentSnapshot item);

}

private OnItemSelectedListener mListener;


public ItemCartRecyelerAdapter(Query query, OnItemSelectedListener listener) {
    super(query);
    mListener = listener;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    return new ViewHolder(inflater.inflate(R.layout.item_cart_adapter,parent,false));
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    holder.bind(getSnapshot(position), mListener);
}

public void deleteItem(int position){
    getSnapshot(position).getReference().delete();
}


static class ViewHolder extends RecyclerView.ViewHolder {
    TextView item_name, item_company, item_price, discount_price, discount;
    ImageView item_image, subtract_image;
    ElegantNumberButton quantityPicker;

    private int TotalPrice = 0;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        item_image = itemView.findViewById(R.id.itemImageView);
        item_company = itemView.findViewById(R.id.item_company);
        item_price = itemView.findViewById(R.id.item_price);
        item_name = itemView.findViewById(R.id.item_name);
        quantityPicker = itemView.findViewById(R.id.quantityPicker);
        subtract_image = itemView.findViewById(R.id.subtract_image);
        discount_price = itemView.findViewById(R.id.item_discount_price);
        discount = itemView.findViewById(R.id.discount);

    }

    public void bind(final DocumentSnapshot snapshot, final OnItemSelectedListener listener) {

        final Attachment attachment = snapshot.toObject(Attachment.class);
        Resources resources = itemView.getResources();


        item_name.setText(attachment.getItem_name());
        item_company.setText(attachment.getItem_brand());
        discount.setText(String.valueOf(attachment.getItem_discount()) + "%\noff");
        quantityPicker.setNumber(String.valueOf(attachment.getItem_quantity()));


        if (attachment.getItem_discount() != null && attachment.getItem_discount() != 0) {
            subtract_image.setVisibility(View.VISIBLE);
            discount_price.setVisibility(View.VISIBLE);
            discount.setVisibility(View.VISIBLE);

            Integer discountedPrice = attachment.getItem_price() * attachment.getItem_discount() / 100;
            Integer priceDiscounted = attachment.getItem_price() - discountedPrice;
            discount_price.setText(String.valueOf(priceDiscounted));
        }

        Log.d(TAG, "bind: Urs: " + attachment.getUrls());
        for (Map.Entry<String, String> result : attachment.getUrls().entrySet()) {
            String key = result.getKey();
            String value = result.getValue();
            Log.d(TAG, "bind: Urls+valuew" + key + value);

            //Load Image
            Glide.with(item_image.getContext())
                    .load(value)
                    .into(item_image);
        }


        quantityPicker.setRange(0, 10);

        quantityPicker.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {


            @Override
            public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
                Log.d(TAG, "onValueChange: postion " + attachment.getItem_id());
                Log.d(TAG, String.format("oldValue: %d   newValue: %d", oldValue, newValue));

                passData(newValue, attachment.getItem_id(), oldValue);

            }


            private void passData(int newValue, String item_id, int oldValue) {
                // Go to the details page for the selected restaurant

                //sharing to seperate cart node in store

                if (newValue == 0) {
                    FirebaseFirestore updateQ = FirebaseFirestore.getInstance();
                    DocumentReference CartREf = updateQ.collection("Cart")
                            .document(item_id);
                    CartREf.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.d(TAG, "onSuccess: Succed to quantity");
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.d(TAG, "onFailure: Failed to change cart");
                        }
                    });

                    FirebaseFirestore dQ = FirebaseFirestore.getInstance();
                    DocumentReference QuanityRef = dQ.collection("fruits & vegetables")
                            .document("UyGXpk2n1A6mHsUcYjCi")
                            .collection("Organic Fruits")
                            .document(item_id);
                    QuanityRef.update("item_quantity", newValue).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.d(TAG, "onSuccess: Success updated item_quanity in Products");
                        }
                    });
                }

                Log.d(TAG, "passData: new update StrARTED");
                FirebaseFirestore updateQ = FirebaseFirestore.getInstance();
                DocumentReference CartREf = updateQ.collection("Cart")
                        .document(item_id);
                CartREf.update("item_quantity", newValue).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "onSuccess: Succed to quantity");
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, "onFailure: Failed to change cart");
                    }
                });

                Log.d(TAG, "passData: new update StrARTED");
                FirebaseFirestore dQ = FirebaseFirestore.getInstance();
                DocumentReference QuanityRef = dQ.collection("fruits & vegetables")
                        .document("UyGXpk2n1A6mHsUcYjCi")
                        .collection("Organic Fruits")
                        .document(item_id);
                QuanityRef.update("item_quantity", newValue).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "onSuccess: Succed to quantity");
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, "onFailure: Failed to change cart");
                    }
                });
            }
        });


        int items_price = attachment.getItem_price() * attachment.getItem_quantity();
        item_price.setText("INR " + items_price + "Rs");

        TotalPrice += TotalPrice + items_price;
        Log.d(TAG, "bind: Toatal = " + TotalPrice);

        //Click Listener
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.OnItemSelected(snapshot);
                }
            }
        });

    }

我尝试过这种方式,但我只能得到单项结果。

    int items_price = attachment.getItem_price() * attachment.getItem_quantity();
    item_price.setText("INR " + items_price + "Rs");

    TotalPrice += TotalPrice + items_price;
    Log.d(TAG, "bind: Toatal = " + TotalPrice);

【问题讨论】:

    标签: android firebase android-studio android-layout google-cloud-firestore


    【解决方案1】:
    private int items_total_price =0;
    
    
      public void bind(final DocumentSnapshot snapshot, final OnItemSelectedListener 
         listener) {
    
        final Attachment attachment = snapshot.toObject(Attachment.class);
        items_total_price+=attachment.getItem_price()
    
        //////////// } //when the recycle view comes to the last item you will have the total items' price
    

    【讨论】:

    • 我按你说的方法试过了,但无法得到总数。仅查看单个项目总数
    • @Shivas 您看到的是哪个商品的价格?最后一个?
    • @ArunYogeshwaran 是的,如果仅使用最后一项显示
    【解决方案2】:

    你必须这样做

    onBindViewHolder

    private int total_price = 0;
    
    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        final Attachment attachment = getSnapshot(position).toObject(Attachment.class);
        total_price += attachment.getItem_price()
    }
    

    【讨论】:

    • 这是错误的......价格会随着滚动而无休止地上涨,因为事情会反弹(另一个错误出于同样的原因)。
    • @Shivas 您的实现问题是您将 firebase Query 对象直接发送到 Recyclerview 并查询 RV 内的 firebase。这是不正确的。从视图(Activity 或 Fragment)中,使用 firebase 查询获取对象列表并将其传递给 RecyclerView。然后就可以轻松计算总价了
    • @RyanM 是的,价格没有按预期工作。可以做什么?
    • @ArunYogeshwaran 好吧,我确实使用了这个,因为 firestoreAdapter 被大大简化了。所以我去了!
    【解决方案3】:

    这有点棘手。如果您正在开发基于服务器的应用程序,则可以查询 db 中的值,但是当您使用 firebase BAAS 时,我遇到了同样的问题,因为您无法编写 SQL 之类的查询来汇总购物车中商品的值。我使用 sqlite 存储将项目添加到 sqlite 的值并执行值的总和并显示购物车中项目的总和

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 2022-12-29
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多