我有OrderCart,我想从中获取所有商品价格的总和,以便向用户显示总价
这是我的Order类,它具有字符串价格属性
public class Order {
private String mID;
private String mName;
private String mPrice;
public Order(){
}
public Order(String id, String name, String price)
{
mID = id;
mName = name;
mPrice = price;
}
public String getmID() {
return mID;
}
public String getmName() {
return mName;
}
public String getmPrice() {
return mPrice;
}
这是一个用于检索数据的firebase采用者的类。采用者显示OrderCart父级下的所有子项,总和应显示在采用者下方,但是它给出了错误
public class PlaceOrder extends AppCompatActivity {
private RecyclerView mOrderList;
private DatabaseReference mDatabase;
private int total_amount=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_orders);
mOrderList = (RecyclerView) findViewById(R.id.order_layout);
mOrderList.setHasFixedSize(true);
mOrderList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance().getReference().child("OrderCart");
FirebaseRecyclerAdapter<Order, OrderViewHolder> FBRA = new FirebaseRecyclerAdapter<Order, OrderViewHolder>(
Order.class,
R.layout.single_order,
OrderViewHolder.class,
mDatabase
) {
@Override
protected void populateViewHolder(OrderViewHolder viewHolder, Order model, int position) {
viewHolder.setmID(model.getmID());
viewHolder.setmName(model.getmName());
viewHolder.setmPrice(model.getmPrice());
}
};
mOrderList.setAdapter(FBRA);
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapScore : dataSnapshot.child("OrderCart").getChildren()) {
total_amount += Integer.parseInt(String.valueOf(snapScore.child("mPrice").getValue()));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
TextView item_price = (TextView) findViewById(R.id.price);
item_price.setText(total_amount);
}
现在,当我尝试显示总金额时,应用会崩溃,以便如何正确检索数据?
答案 0 :(得分:0)
尝试这种方式,使用迭代器读取数据。
在onDataChange内部,
Iterator<DataSnapshot> dataSnapshotsorder = dataSnapshot.child("OrderCart").getChildren().iterator();
while (dataSnapshotsorder .hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshotsChat.next();
total_amount += Integer.parseInt(String.valueOf(dataSnapshotChild .child("mPrice").getValue()));
}