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

萝らか妹 提交于 2020-01-05 05:10:37

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/40260334/how-to-detect-if-valueeventlistener-has-fetched-data-or-not-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!