wait until firebase retrieves data

后端 未结 9 1123
不思量自难忘°
不思量自难忘° 2020-11-29 08:33

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

public String getMessage(){

           


        
9条回答
  •  既然无缘
    2020-11-29 09:02

    You can use CountDownLatch. This is how you can use it.

    public String getMessage(){
       CountDownLatch done = new CountDownLatch(1);
       final String message[] = {null}; 
       root.child("MessagesOnLaunch").child("Message").addListenerForSingleValueEvent(new ValueEventListener() {
    
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            message[0] = (String) dataSnapshot.getValue();
            System.out.println("worked");
            done.countDown();
        }
    
        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("failed"+firebaseError.getMessage());
        }
    });
    
    try {
        done.await(); //it will wait till the response is received from firebase.
    } catch(InterruptedException e) {
        e.printStackTrace();
    }
    return message[0];
    }
    

提交回复
热议问题