wait until firebase retrieves data

2020-02-05 06:39发布

I want to build a method that returns a child value in FireBase. I tried to do something like this:

public String getMessage(){

    root.child("MessagesOnLaunch").child("Message").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            message = (String) dataSnapshot.getValue();
            Log.i("4r398", "work");
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.e("error", firebaseError.getMessage());
        }
    });
    return message;
}

The problem is that the method returns null that is probably because the method doesn't wait until the listener finishes and return null because its the default value of message. How can I make this method wait until the listener occurs and then return the value.

7条回答
霸刀☆藐视天下
2楼-- · 2020-02-05 07:08

As @CMikeB1 commented on another response in the java world when we are dealing with servlets and services rest we use sync calls to perform operations, it would be useful to have both options in sdk firebase admin so that the developer could choose which one to use depending on his case use.

I made my implementation from waiting to read the sync data using ApiFuture which is the current interface adopted by the sdk of the firebase admin. here's a link!

public DataSnapshot getMessage() {
    final SettableApiFuture<DataSnapshot> future = SettableApiFuture.create();
    databaseReference.child("MessagesOnLaunch").child("Message").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            future.set(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            future.setException(databaseError.toException());
        }
    });
    try {
        return future.get();
    } catch(InterruptedException | ExecutionException e) {
        e.printStackTrace();
        return null;
    }
}
查看更多
登录 后发表回答