我得到的所有时间都返回false,但我有数据。我怎样才能得到真实的结果。有人请帮我解决这个问题。
public boolean checkVechicalNumberONCheckIN(final String Vehicle_no,final Context context){
car_return2 = false;
sharedPreference = new SharedPreference();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("raw_check_in").orderByChild("vechical_number").equalTo(Vehicle_no);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
car_return2 = true;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return car_return2; //here i get all time false
}
答案 0 :(得分:2)
firebase查询是异步的,因此您不会立即获得结果,而是需要从onDataChange
调用一些方法,该方法将包含您要执行的代码,一旦获得结果
public void checkVechicalNumberONCheckIN(final String Vehicle_no,final Context context){
sharedPreference = new SharedPreference();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("raw_check_in").orderByChild("vechical_number").equalTo(Vehicle_no);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
executeSomeMethodOnResult(dataSnapshot.exists());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
void executeSomeMethodOnResult(boolean flag){
if(flag){// mean true}else{// flag is false}
}
或者如果这是一个帮助类,那么最佳选择是创建回调机制