Darshan Soni
Darshan Soni

Reputation: 1809

How to detect if ValueEventListener has fetched data or not in Firebase

I'm using following code to fetch the data from Firebase DB but as it makes network request in background thread so I want to wait till it completes the request and get a value. For example,

boolean isAvailable=false;
    usernameReference.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        isAvailable = true;
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        progressBar.setVisibility(View.GONE);
                    }
                });
if(isAvailable){
       //do something here
}
else{
      //do something here 
}

This snippet always execute the else part so I want to wait till the variable isAvailable get the value from database then further Execution will take place.

Upvotes: 1

Views: 870

Answers (1)

Akshay Bhat 'AB'
Akshay Bhat 'AB'

Reputation: 2700

First create an interface like this:

public interface IsAvailableCallback {
    void onAvailableCallback(boolean isAvailable);
}

Suppose your above code is in this method which takes interface object to trigger callback like :

public void isAvailable(IsAvailableCallback callback) {
    boolean isAvailable=false;
    usernameReference.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    isAvailable = true;
                    //this will trigger true
                    callback.onAvailableCallback(isAvailable);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    progressBar.setVisibility(View.GONE);
                    //this will trigger false
                    callback.onAvailableCallback(isAvailable);
                }
            });                
}

Call this method like :

isAvailable(new IsAvailableCallback() {
    @Override
    public void onAvailableCallback(boolean isAvailable) {
        //you will get callback here, Do your if condition here
    }
}

Upvotes: 4

Related Questions