0

I've been trying to extract informations from Firebase Realtime database to my desktop Java application and I'm confused with how the ChildeventListener works so;

public void getInformation(){
    DatabaseReference ref = FirebaseDatabase.getInstance()
    .getReference().child("Users/Informatique/LFI1");
    Query myq = ref.orderByChild("Presences");
    myq.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildName) {

            Map <String, String> map = new HashMap <String, String>();
            map = (Map<String, String>) snapshot.child("Presences").getValue();


            for(Map.Entry<String,String> entry : map.entrySet()){

               System.out.println(entry.getValue());
               list.add(entry.getValue());

            }

         }


     });
     System.out.println(list.size());
}  

The values i get in the output is what I need but the list's size after all that is 0 and can't be use else where yet if you check the size inside the onChildAdded method you get the right one.

0
< 12345678 Skander Maranissi LFI1 Wed May 02 15:52:03 GMT+01:00 2018 >
< 12345678 Mohsen Yajour LFI1 Wed May 02 15:09:32 GMT+01:00 2018 >
< 12345678 Lebron James LFI1 Wed May 02 16:51:35 GMT+01:00 2018 >
< 12345678 Lebron James LFI1 Sat May 05 12:54:02 GMT+01:00 2018 >

How is it printing the list's size then looping through the map; this is what's not clear in my mind about how Listeners work. Thanks a lot.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

You cannot get the size of a list now that hasn't been loaded yet. With other words, you cannot simply call list.size() outside the onChildAdded() method because it will always be 0 due the asynchronous behaviour of this method. This means that by the time you are trying to get the size of the list outside that method, the data hasn't finished loading yet from the database and that's why the size is always 0. A quick solve for this problem would be to use list.size() only inside the onChildAdded() method or if you want to use it outside, I recommend you see the last part of my anwser from this post in which I have exaplined how it can be done using a custom callback. You can also take a look at this video for a better understanding. Remember, onDataChange() method has the same behaviour as onChildAdded() method.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193