В списке корзин, который у меня есть, проблема заключается в том, что когда товаров в списке корзин больше 4, общая цена не включает цену остальных товаров, пока я не прокрутите вниз, тогда к общей цене добавятся товары остальных. цена в, но я хочу, чтобы, когда пользователь открывает, он показывает общую стоимость всех предметов без прокрутки. Надеюсь, что кто-то может помочь мне выяснить, в чем проблема, Спасибо
Ниже приведен код активности корзины:
public class CartActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private TextView txtTotalAmount;
private Button resetbtn;
public CheckBox checkBox;
private static DecimalFormat df = new DecimalFormat("#.00");
private double MemTotalPrice =0;
private double TotalPrice =0;
private boolean count = true;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
initWidgets();
setOnClickListeners();
recyclerView = findViewById(R.id.cart_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
checkBox = findViewById(R.id.checkBox);
txtTotalAmount = findViewById(R.id.total_price);
}
private void setOnClickListeners(){
resetbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(CartActivity.this);
builder.setTitle("Alert");
builder.setMessage("Are you sure you want to reset?");
builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DatabaseReference cartListRef =FirebaseDatabase.getInstance().getReference().child("Cart List");
cartListRef.removeValue();
Intent intent = new Intent(CartActivity.this, MainActivity.class);
startActivity(intent);
}
});
android.app.AlertDialog alert2 = builder.create();
alert2.show();
}
});
}
private void initWidgets()
{
resetbtn = findViewById(R.id.resetbutton);
}
@Override
public void onStart()
{
super.onStart();
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartListRef.child("Cart")
.child(("Products")), Cart.class)
.build();
FirebaseRecyclerAdapter<Cart, CartViewHolder> adapter = new FirebaseRecyclerAdapter<Cart, CartViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull final CartViewHolder cartViewHolder, final int i, @NonNull final Cart cart)
{
cartViewHolder.btn_quantity.setNumber(cart.getQuantity());
cartViewHolder.txtProductPrice.setText("Price = RM"+cart.getPrice());
cartViewHolder.txtProductName.setText(cart.getProductName());
cartViewHolder.btn_quantity.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
@Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue)
{
cart.setQuantity(String.valueOf(newValue));
cartListRef.child("Cart").child("Products").child(cart.getProductName()).child("quantity").setValue(String.valueOf(newValue));
if(oldValue > newValue){
TotalPrice = TotalPrice - Double.valueOf(cart.getPrice());
}
else if(newValue > oldValue){
TotalPrice += (Double.valueOf(cart.getPrice()));
}
count = false;
}
});
if(count){
TotalPrice += (Double.valueOf(cart.getPrice()) * Double.valueOf(cart.getQuantity()));
}
count = true;
cartViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence options [] = new CharSequence[]{
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0)
{
cartListRef.child("Cart")
.child("Products")
.child(cart.getProductName())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(CartActivity.this, "Item removed successfully.",Toast.LENGTH_SHORT).show();;
Intent intent = new Intent(CartActivity.this, MainActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
txtTotalAmount.setText("Total Price = RM " + df.format(TotalPrice));
}
@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout,parent,false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
}
База данных Firebase в реальном времени:
{
"Cart List" : {
"Cart" : {
"Products" : {
"BenQ" : {
"MemPrice" : "150",
"Price" : "300",
"ProductName" : "BenQ",
"date" : "19 Jan 2020",
"quantity" : "1",
"time" : "23:28:08 p.m."
},
"Dell" : {
"MemPrice" : "5000",
"Price" : "10000",
"ProductName" : "Dell",
"date" : "19 Jan 2020",
"quantity" : "1",
"time" : "23:27:13 p.m."
},
"IBM" : {
"MemPrice" : "200",
"Price" : "400",
"ProductName" : "IBM",
"quantity" : "1"
},
"KDK" : {
"MemPrice" : "25",
"Price" : "50",
"ProductName" : "KDK",
"quantity" : "1"
},
"Logitech" : {
"MemPrice" : "5",
"Price" : "10",
"ProductName" : "Logitech",
"date" : "17 Jan 2020",
"quantity" : "1",
"time" : "03:07:18 a.m."
}
}
}
},
"Product" : {
"Product1" : {
"Barcode" : "112233",
"MemPrice" : "5",
"Price" : "10",
"ProductName" : "Logitech"
},
"Product2" : {
"Barcode" : "123456",
"MemPrice" : "5000",
"Price" : "10000",
"ProductName" : "Dell"
},
"Product3" : {
"Barcode" : "778899",
"MemPrice" : "150",
"Price" : "300",
"ProductName" : "BenQ"
}
}
}
Ниже приведены скриншоты:
1) В корзине 5 товаров. Общая цена должна быть 10760, но она показывает 10750, то есть общая цена 4 предметов и не добавлена цена 5-го предмета в корзине До прокрутки вниз
2) После прокрутки вниз добавлена цена 5-го предмета После прокрутки вниз