我正在尝试计算数据库中所有名为“价格”的子项的价值总和
下面是我的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mtotal = (TextView) findViewById(R.id.textre);
mda = FirebaseDatabase.getInstance().getReference().child("Cart");
mda.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object price = map.get("Price");
int pvalue = Integer.parseInt(String.valueOf(price));
sum += pvalue;
if (sum<100){
Toast.makeText(getApplicationContext(),"greare",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"sorry",Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
如我的代码所示,如果从价格节点获得的值小于100,则应该显示一条吐司消息,说“成功”。相反,该应用程序崩溃时没有任何消息
图像是我的Firebase数据库的视图,显示了我希望获取的值“ Price”
答案 0 :(得分:1)
尝试执行此操作,我认为您没有正确获得Price值
mda.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
int pvalue = ds.child("Price").getValue(Integer.class);
sum += pvalue;
if (sum<100){
Toast.makeText(getApplicationContext(),"greare",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"sorry",Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});