0

I need to return a read data from Firebase. Here is the code:

private String getInfo(DatabaseReference reference) {
   String string = "";
   reference.child("xxx").addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
       string = snapshot.getValue().toString();
       // here the log display the correct value I need
       Log.i("Log", string);  
   }

   onCancelled() ...
   }
});
return string; // HERE THE VALUE IS NULL!!!!

As written above the log show the correct value, but when I try to return it its value becomes null.

GFriends
  • 35
  • 5
  • That's the classic issue with asynchronous programming. Note that Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a custom callback or other two options mentioned in this [article](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Jul 05 '21 at 14:19

2 Answers2

0

It's within the inner block, that's why it happens Move the return function to the inside of the block so it will show the correct value

ADITYA RANADE
  • 293
  • 3
  • 10
  • If I move the return statement in the inner block it says me that the method is void and can't return the value – GFriends Jul 05 '21 at 13:31
0

First try moving the return string; inside the method body, then if it doesn't help read below.

addListenerForSingleValueEvent() executes onDataChange method immediately and after executing that method once, it stops listening to the reference location it is attached to.

So instead use addValueEventListener(), which keeps listening to the query or database reference it is attached to as mentioned here Read and Write Data on Android

Here is another useful information from the official documentation:

The listener receives a DataSnapshot that contains the data at the specified location in the database at the time of the event. Calling getValue() on a snapshot returns the Java object representation of the data. If no data exists at the location, calling getValue() returns null.

In this example, ValueEventListener also defines the onCancelled() method that is called if the read is canceled. For example, a read can be canceled if the client doesn't have permission to read from a Firebase database location. This method is passed a DatabaseError object indicating why the failure occurred.

Tomino
  • 475
  • 2
  • 15