0

If you call a Firebase method like below and then create a while loop which waits for a change to be made by this method, onDataChange is never invoked. The while loop prevents this from happening. But, why does this happen? Shouldn't asynchronous method like onDataChange do its job regardless of what you do outside of this method?

The method I am talking about :

public static void readLeagueStandings(){

    DatabaseReference leagueStandingsDbRef = firebaseDatabase.getReference("league-standings");
    leagueStandingsDbRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                LeagueStandings leagueStandings = objectMapper.convertValue(snapshot.getValue(), LeagueStandings.class);
                LocalInfo.leagueStandings.add(leagueStandings);
            }
            leagueStandings = true;
        }
        @Override
        public void onCancelled(DatabaseError error) {
            error.toException();
        }
    });
}
  • make sure two things 1) you're not trying to do anything when this function returns expecting the data is loaded. 2) the reference you're trying to access actually exists and has data under it – Abhinav Chauhan Mar 28 '20 at 15:20
  • Your `while` loop is likely what is known as a tight loop, which means that it blocks the main thread of the app from doing anything else. The proper way to handle the asynchronous call is to either include the code in the `onDataChange` or create a custom callback. See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Mar 28 '20 at 15:50

0 Answers0