0

I want to make an ArrayList with all the user ids found by a call to a database. This is how I currently do it:

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot ds : dataSnapshot.getChildren()) {
         userId= ds.getKey();
         users.add(userId); // adding each user to the ArrayList called users
    }
}

So far so good, I add each user to the arraylist. But now I need to do operations on that arraylist outside the callback. However, it is not visible outside that scope, which makes sense because it's async and you can't tell when it's finished or not. So what is the best way? For example I can't even do the simplest operation such as outputing the ids, if it's outside the listener:

int listSize = users.size();
for (int i = 0; i<listSize; i++){
    Log.d("tag: ", users.get(i));
    }
}

If the above code is not inside the onDataChange, then I can't call it. What is the correct way to use the array list and make sure it's finished, outside the listener? Or I have to do it inside for each id?

mbuechmann
  • 5,413
  • 5
  • 27
  • 40
pileup
  • 1
  • 2
  • 18
  • 45
  • 1
    Please check the duplicate to see how can you solve this using a custom callback. So you'll be able to do operations with the list outside `onDataChange()` method.. – Alex Mamo Dec 19 '18 at 13:37
  • @AlexMamo thanks. After reading the duplicate, what do you suggest? Should I write all the code inside the `onDataChange` and keep it async as intented, or use the method shown in the duplicate? – pileup Dec 19 '18 at 13:57
  • 2
    If you need that data only in one place, you can use only inside the `onDataChange()` method otherwise, create that custom callback and use it outside. – Alex Mamo Dec 19 '18 at 14:00

0 Answers0