我正在尝试创建购物车应用程序。这就是我的Firebase数据库的外观Firebase database
所以我已经使用他们的用户ID存储了每个用户的购物车详细信息。
这是我的代码:
DatabaseReference dataRef = FirebaseDatabase.getInstance().getReference("cart_details/" + uid);
dataRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long c = dataSnapshot.getChildrenCount();
int count = (int) c;
String show = "PRODUCT NAME QUANTITY PRICE";
if (count > 0) {
for (int i = 1; i <= count; i++) {
final LinearLayout la = new LinearLayout(getBaseContext());
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
la.setOrientation(LinearLayout.HORIZONTAL);
final TextView tv = new TextView(getBaseContext());
final ImageButton btn1 = new ImageButton(getBaseContext());
final int j = i;
FirebaseAuth auth1 = FirebaseAuth.getInstance();
String Uid = auth1.getCurrentUser().getUid();
final DatabaseReference dataref1 = FirebaseDatabase.getInstance().getReference("cart_details/" + Uid + "/cart_" + i);
dataref1.addValueEventListener(new ValueEventListener() {
String pName;
String pQty_bag;
String pPrice_bag;
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Product pro = dataSnapshot.getValue(Product.class);
pName = pro.name;
pQty_bag = pro.quantity;
pPrice_bag = pro.price;
//text
tv.setText("\n" + pName + " " + pQty_bag + " " + pPrice_bag);
tv.setTextColor(ColorStateList.valueOf(Color.BLACK));
la.addView(tv);
//button
btn1.setId(j + 1);
btn1.setBackground(getResources().getDrawable(R.drawable.remove));
btn1.setLayoutParams(params);
final int index = j;
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dataref1.removeValue();
}
});
la.addView(btn1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
layout.addView(la);
}
} else {
show = "There are no Items in the Cart";
pay.setEnabled(false);
}
showCartContent.setText(show);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
在代码中,我遍历特定用户ID和内部的条目数,然后我检索每个购物车项的所有值。 此外,对于每个购物车项目,我添加了一个图像按钮(删除),点击后应该删除该项目。
这就是输出的显示方式
现在我的问题是如何删除项目,我尝试使用ref.removeValue();但我一直在崩溃。
这是崩溃日志crash log