如何检测ValueEventListener是否在Firebase中提取了数据

时间:2016-10-26 10:51:21

标签: android firebase firebase-realtime-database

我正在使用以下代码从Firebase DB获取数据,但因为它在后台线程中发出网络请求,所以我想等到它完成请求并获取值。例如,

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 
}

这段代码总是执行else部分,所以我想等到变量isAvailable从数据库中获取值,然后进一步执行。

1 个答案:

答案 0 :(得分:3)

首先创建一个这样的界面:

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

假设您的上述代码在此方法中,该方法使接口对象触发回调,如:

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

将此方法称为:

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