我正在尝试从数据库中获取某种数据,但是它一直为我提供null值。
verifyPromo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String promoCodeString = promoCode.getEditText().getText().toString();
Query query = FirebaseDatabase.getInstance().getReference().child("promoCodes").orderByChild("promoCode").equalTo(promoCodeString);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() & promoUnapplied) {
Map<String, String> promoCodeInfo = (Map<String, String>) dataSnapshot.getValue();
String amount = promoCodeInfo.get("amount");
double bill = Double.valueOf(theBillTA.getText().toString());
double billAfterDis = bill * Double.valueOf(amount) / 100;
bill -= billAfterDis;
theBillTA.setText(String.valueOf(bill));
promoUnapplied = false;
Toast.makeText(NewAppointmentTA.this, "Grate,You Got A Discount", Toast.LENGTH_SHORT).show();
} else if (dataSnapshot.exists() & !promoUnapplied) {
Toast.makeText(NewAppointmentTA.this, "You Already Get A Discount", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(NewAppointmentTA.this, "The Promo Code you Entered Is Not Exist", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
});
我调试了代码,并显示“数量”为空。 我包括了调试的图片:
这是数据库树:
答案 0 :(得分:0)
对Firebase数据库执行查询时,可能会有多个结果。因此,快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。
这意味着您的代码需要通过遍历dataSnapshot.getChildren()
来处理快照的列表方面:
Query query = FirebaseDatabase.getInstance().getReference().child("promoCodes").orderByChild("promoCode").equalTo(promoCodeString);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (promoUnapplied) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String amount = snapshot.child("amount").getValue(String.class);
double bill = Double.valueOf(theBillTA.getText().toString());
double billAfterDis = bill * Double.valueOf(amount) / 100;
bill -= billAfterDis;
...