当数据不存在时,Toast 不起作用



当Firebase数据库中不存在数据时,我的Toast不起作用。发生什么事?

public void searching(final String id){
DatabaseReference databaseReference = FirebaseDatabase.getInstance()
.getReference("Employee");
Query query = databaseReference.orderByChild("id").equalTo(id);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("id").exists()) {
Employee employee = data.getValue(Employee.class);
hp.setText(employee.getPhoneNum());
address.setText(employee.getAddress());
fullName.setText(employee.getFullName());
Ic.setText(employee.getIcNum());
Sex.setText(employee.getSex());
emailVerify.setText(employee.getEmail());
getData.setVisibility(View.GONE);
update.setVisibility(View.VISIBLE);
fullName.setVisibility(View.VISIBLE);
Ic.setVisibility(View.VISIBLE);
tAddress.setVisibility(View.VISIBLE);
tPhone.setVisibility(View.VISIBLE);
hp.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
Sex.setVisibility(View.VISIBLE);
}else{
Toast.makeText(getContext(),"Please Enter Correct Employee ID",
Toast.LENGTH_SHORT).show();
return;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

在这种情况下,您的查询可能无法databaseReference.orderByChild("id").equalTo(id)获取任何记录,因此它不会执行 for 循环,因此您可以先检查子项的数量是否大于 0。

你可以试试这种方式,比如:

if (dataSnapshot.dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("id").exists()) {
Employee employee = data.getValue(Employee.class);
hp.setText(employee.getPhoneNum());
address.setText(employee.getAddress());
fullName.setText(employee.getFullName());
Ic.setText(employee.getIcNum());
Sex.setText(employee.getSex());
emailVerify.setText(employee.getEmail());
getData.setVisibility(View.GONE);
update.setVisibility(View.VISIBLE);
fullName.setVisibility(View.VISIBLE);
Ic.setVisibility(View.VISIBLE);
tAddress.setVisibility(View.VISIBLE);
tPhone.setVisibility(View.VISIBLE);
hp.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
Sex.setVisibility(View.VISIBLE);
}else{
Toast.makeText(getContext(),"Please Enter Correct Employee ID",
Toast.LENGTH_SHORT).show();
return;
}
}
} else {
Toast.makeText(getContext(),"No data found.",
Toast.LENGTH_SHORT).show();
}

dataSnapshot.getChildren()为空时,您不会输入for块,因此Toast不会出现。

最新更新