0

I am using a firebase database and i want to loop through all childs of a node. I am using the following code:

   ArrayList<versicherungHelper> versicherungsListe =  new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
.....not relevant coding...

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users/Frank/Versicherungen");

        ref.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    versicherungHelper versicherung = snapshot.getValue(versicherungHelper.class);
                    versicherungsListe.add(versicherung);
                }

            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }


        });


        Snackbar snackbar = Snackbar.make(findViewById(R.id.drawer_layout),String.valueOf(versicherungsListe.size()),Snackbar.LENGTH_SHORT);
        snackbar.show();

when i check the length of the list "versicherungsListe" inside the for-loop, the result is not 0. when i check the length of the list after the listener, the result is 0.

How can that be? The array list is defined outside the onCreate-method, as you can see.

I would highly appreciate an answer :) Thank you very much!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Data is loaded from Firebase asynchronously, so your `Snackbar.make(...)` runs before any of the `versicherungsListe.add(versicherung)` is executed. Any code that needs data from the database, needs to be inside `onDataChange` or called from there. – Frank van Puffelen Mar 03 '21 at 23:02
  • Thanks for the fast answer! Do you know if there is another possibility to read all children of a node into an array? I need this list to work with. I just find these different onEvent solutions in the internet. Thanks a lot! – Frank Wühr Mar 04 '21 at 08:29
  • Data is loaded from Firebase (and most modern cloud APIs) asynchronously. While there may be platforms where that is optional, on Android it isn't as loading the data synchronously would block the user from interacting with your app. If you move the calls to `Snackbar.make(...)` and `Snackbar.show()` *into* `onDataChange` they can use the data at the right moment. – Frank van Puffelen Mar 04 '21 at 15:05
  • Ok I will try that. Thanks a lot ! – Frank Wühr Mar 04 '21 at 16:28

0 Answers0