0

I am trying to make it so that I can easily fetch the value of any path in my Realtime Database. I had 2 different ways of doing it. They are below.

Method 1:

public Task<DataSnapshot> getValue(String path) {
     return database.getReference(path).get();
}

Method 2:

public Object fetch(String path) {
     Object value;
     Task<DataSnapshot> task = database.getReference(path).get();
     while (!task.isSuccessful());
     value = task.getResult().getValue();
     return value;
}

For whatever reason, if I add an onCompleteListener to the output of the first function and do all of my code inside it, it works perfectly fine, but if I try and wait for it to be successful (method 2), it just gets stuck on the while loop forever. What is even weirder is that the exact code worked perfectly fine on a different project, so I am not really sure what's wrong.

I would totally just use method one except it doesn't always complete it at the same speed the rest of the program is going, so then the program ends up trying to get a method that hasn't been given its value yet.

If anyone has any ideas on how to get Method 2 to work please do share

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Pluto7073
  • 39
  • 3
  • This won't work: `while (!task.isSuccessful())`. Instead of using such a tight loop for the task to complete, you should add a completion handler to the task and then use the data inside the `onComplete`/`onSuccess` method of that. Also see: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Apr 08 '22 at 03:35

1 Answers1

0

When using the following line of code:

while (!task.isSuccessful());

The while statement has no body, since you are adding a ; (semicolon) at the end of the line. This means that while statement ends there. You can either create a body:

                              
 while (!task.isSuccessful()) {
     // ...
 }

Or most likely you should use an if statement rather than a while:

public Object fetch(String path) {
     Object value;
     Task<DataSnapshot> task = database.getReference(path).get();
     if (task.isSuccessful()) {
         value = task.getResult().getValue();
     }
     return value;
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193