0
public List<Song> retrieveSongs() {
    List<Song> dbSongs = new ArrayList<>();
    db = FirebaseDatabase.getInstance().getReference().child("songs");
    db.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            dbSongs.clear();
            for (DataSnapshot s : snapshot.getChildren()) {
                Song song = s.getValue(Song.class);
                dbSongs.add(song);
            }
            Log.d("SONGSSSS", String.valueOf(dbSongs.size()));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
    return dbSongs;
}

the size of the returned list dbSongs is always 0 although it's not in the log statment as if when im out of the listener, the list is cleared. and i dont understand why. i even made sure that the snapshot contains data and it does.

i tried to retrieve an array of Song object from the database that looks like the following:

songs:
     |song1
     |song2
     |song3

i made sure that i am retrieving the correct snapshot of data that i want. but when the function returns, it is returning an empty array.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Mals
  • 31
  • 1
  • 3
  • Data is loaded from Firebase (and most modern cloud APIs) asynchronously. If you add some logging or run in a debugger, you'll see that `return dbSongs` runs before `onDataChange` is called and thus returns an empty list. There is no way to change this behavior. Any code that needs the data from the database, needs to be inside `onDataChange`, be called from there, or be otherwise synchronized. See the questions I linked for more on these options. – Frank van Puffelen Jan 15 '23 at 21:39
  • If you understand Kotlin, I think that this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5) will help. Here is the corresponding [repo](https://github.com/alexmamo/RealtimeDatabase). – Alex Mamo Jan 16 '23 at 08:49

0 Answers0