0

I am trying to add a value from onDataChanged method inside a for loop. each time whenever for loops is getting executed then the value will be added to the arraylist. now my problem is i cannot return that arraylist. it is showing null object.

ArrayList<BookingRequest> bookedSlot;
BookingRequest currRequet;


   req.orderByChild("b_id").equalTo("01").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                currRequet = snapshot.getValue(BookingRequest.class); // you
                bookedSlot.add(snapshot.getValue(BookingRequest.class));
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }


    });


}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Karthick Jai
  • 61
  • 1
  • 11
  • 1
    Data is loaded from Firebase asynchronously. The only place you can be certain the data is available, is inside the `onDataChange`. For this reason any code that needs the data from the database, must be inside `onDataChange` or be called from there. See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Jan 04 '20 at 22:47
  • 1
    Also: please don't ever leave `onCancelled` empty. While it's not the cause of the problem you have now, it may hide other problems in the future. The minimum implementation of `onCancelled` should be `public void onCancelled(@NonNull DatabaseError databaseError) { throw databaseError.toException(); }`. – Frank van Puffelen Jan 04 '20 at 22:48
  • @FrankvanPuffelen i have tried your solution but it is still getting null outside of OnDataChanged. – Karthick Jai Jan 05 '20 at 04:31

0 Answers0