Home > Back-end >  Realtime Display Value Change form Firebase
Realtime Display Value Change form Firebase

Time:12-14

I am new to android studio and currently watching tutorials. As of now I have a Shopping cart activity where I can increment, decrement and delete items in cart. The thing is whenever I delete, add or deduct an item, the cart values does not update. I still need to change activities to see the changes. Also the item that I deleted still appears at the bottom of recyclerview items after the dialog appearance unless I change the activity and go back. Please help me how to apply real time update. Below are my class files for the cart activity and adapter class.

CartActivity.java


        @Override
    protected void onStop() {
        if (EventBus.getDefault().hasSubscriberForEvent(MyUpdateCartEvent.class))
            EventBus.getDefault().removeStickyEvent(MyUpdateCartEvent.class);
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED, sticky = true)
    public void onUpdateCart(MyUpdateCartEvent event) {
        loadCartFromFirebase();
    }

private void loadCartFromFirebase() {
        fAuth = FirebaseAuth.getInstance();
        if(fAuth.getCurrentUser() != null){
            userId = fAuth.getCurrentUser().getUid();
        } else {
            userId = "UNIQUE_USER_ID";
        }
        List<CartModel> cartModels = new ArrayList<>();
        FirebaseDatabase.getInstance()
                .getReference("cart")
                .child(userId)
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if (snapshot.exists()) {
                            for (DataSnapshot cartSnapshot : snapshot.getChildren()) {
                                CartModel cartModel = cartSnapshot.getValue(CartModel.class);
                                cartModel.setKey(cartSnapshot.getKey());
                                cartModels.add(cartModel);
                            }
                            cartLoadListener.onCartLoadSuccess(cartModels);
                        } else {
                            cartLoadListener.onCartLoadFailed("Cart Empty");
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        cartLoadListener.onCartLoadFailed(error.getMessage());
                    }
                });
    }

    private void init() {
        ButterKnife.bind(this);

        cartLoadListener = this;
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recycler_cart.setLayoutManager(layoutManager);
        purchScrnBtn.setOnClickListener(v -> startActivity(new Intent(this, PurchaseActivity.class)));

    }

    @Override
    public void onCartLoadSuccess(List<CartModel> cartModelList) {
        double sum = 0;
        for (CartModel cartModel : cartModelList) {
            sum  = cartModel.getTotalPrice();
        }
        textTotal.setText(new StringBuilder("$").append(sum));
        MyCartAdapter adapter = new MyCartAdapter(this, cartModelList);
        recycler_cart.setAdapter(adapter);
    }

MyCartAdapter.java

package com.example.cart.adapter;

public class CartActivity extends AppCompatActivity implements CartLoadListener {


    public MyCartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyCartViewHolder(LayoutInflater.from(context)
                .inflate(R.layout.layout_cart_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyCartViewHolder holder, int position) {
        holder.minus.setOnClickListener(v -> {
            minusCartItem(holder,cartModelList.get(position));
        });
        
        holder.delete.setOnClickListener(v -> {
            AlertDialog dialog = new AlertDialog.Builder(context)
                    .setTitle("Delete item")
                    .setMessage("Do you really want to delete item")
                    .setNegativeButton("CANCEL", (dialogInterface, i) -> dialogInterface.dismiss())
                    .setPositiveButton("OK", (dialogInterface2, i) -> {

                        //Temp remove
                        notifyItemRemoved(position);
                        deleteFromFirebase(cartModelList.get(position));
                        dialogInterface2.dismiss();
                    }).create();
            dialog.show();
        });

    }

    private void deleteFromFirebase(CartModel cartModel) {
        FirebaseDatabase.getInstance()
                .getReference("cart")
                .child(userId)
                .child(cartModel.getKey())
                .removeValue()
                .addOnSuccessListener(aVoid -> EventBus.getDefault().postSticky(new MyUpdateCartEvent()));
    }

    @SuppressLint("SuspiciousIndentation")
    private void minusCartItem(MyCartViewHolder holder, CartModel cartModel) {
        if(cartModel.getQuantity() > 1)
            cartModel.setQuantity(cartModel.getQuantity()-1);
            cartModel.setTotalPrice(cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));

            //update quantity
            holder.txtQuantity.setText(new StringBuilder().append(cartModel.getQuantity()));
            updateFirebase(cartModel);
    }

    public class MyCartViewHolder extends RecyclerView.ViewHolder{

        Unbinder unbinder;

        public MyCartViewHolder(@NonNull View itemView) {
            super(itemView);
            unbinder = ButterKnife.bind(this, itemView);
        }
    }

}

CodePudding user response:

The thing is whenever I delete, add or deduct an item, the cart values does not update.

That's because you load data from Firebase with addListenerForSingleValueEvent, which only loads the data when you call it. If you want to continue to monitor the data for changes, use addValueEventListener instead.

  • Related