gpt4 book ai didi

java - 尝试从 Firebase 数据库获取数据,但总是获取空值

转载 作者:行者123 更新时间:2023-12-01 23:37:35 24 4
gpt4 key购买 nike

我试图从数据库中获取某种数据,但它一直给我空值。

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) {

}
});
}
});

我调试了我的代码,它显示“金额”为空。我附上了调试的图片:

这是数据库树:

enter image description here

最佳答案

当您对 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;
...

关于java - 尝试从 Firebase 数据库获取数据,但总是获取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com