0

I get all time return false but i have data. How can i get return true result. Anybody please help me to solve this question.

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

}
Suman
  • 34
  • 3
  • Possible duplicate of [How to return dataSnapshot value as a result of a method?](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method) – Alex Mamo Apr 23 '18 at 16:52

1 Answers1

2

The firebase queries are asynchronous so you will not get the result immediately, instead you need to call some method from onDataChange which will contain the code that you want to execute, once you get the result

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}
}

or if this is a helper class then the optimal option is to create callback mechanism

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68