这是实时数据库,其中 p_price 是我想要添加以获得购物车总价的产品价格
MainActivity.java
public class MainActivity extends AppCompatActivity {
private DatabaseReference mDatabase;
private ListView mProdList;
private ArrayList<String> mProducts = new ArrayList<>();
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Product");
mProdList = (ListView) findViewById(R.id.prod_list);
textView = (TextView) findViewById(R.id.textView);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mProducts);
mProdList.setAdapter(arrayAdapter);
mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
String value = dataSnapshot.child("p_id").getValue(String.class);
String value1 = dataSnapshot.child("p_name").getValue(String.class);
Integer value2 = dataSnapshot.child("p_price").getValue(Integer.class);
mProducts.add("Product ID: \n" + value);
mProducts.add("Product Name: \n" + value1);
mProducts.add("Product Price: \n" + value2);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
我想显示购物车总价并相应地进行付款 我正在使用默认的数组适配器......如果有人知道如何制作自定义数组适配器,请帮助我
最佳答案
Firebase 已准备好计算总数。您可以尝试下面的代码。
mDatabase = FirebaseDatabase.getInstance().getReference().child("Product");
//Put this code here, after the mDatabase
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int totalPrice = 0;
for (DataSnapshot snapShot : dataSnapshot.getChildren()) {
if (snapShot.exists()) {
int size = snapShot.child("p_price").getValue(Integer.class);
totalPrice += size;
//Display total
textViewTotal.setText(String.valueOf(totalPrice));
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
您可以引用此链接。
https://stackoverflow.com/a/59944838/9346054
您可以像这样建立购物车数据库。
Cart
-userUid
-cartUid
-productUid
-cartUidValue
-dateCreated
-productUidValue
关于java - 我想添加实时 Firebase 数据库中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60013763/