0

Have a problem when getting the children count for my firebase database reference.

I am using a

private long childs;

this variable gets set in onCreate like this:

    ref_1 = new Firebase("https://xxxxxxxxxx-xxxxx.xxxxxxxxx.com/traning/crossfit/level"+condition);
    ref_1.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            childs = dataSnapshot.getChildrenCount();
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

If i debug this code at the dataSnapshot it have counted the children and its correct, but when using this global variable childs on other places in the file there is somehow set to zero.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Possible duplicate of [can't get values out of ondatachange method](https://stackoverflow.com/questions/38456650/cant-get-values-out-of-ondatachange-method) – SUPERCILEX Dec 30 '17 at 02:32

1 Answers1

0

This is happening because onDataChange() method is called asynchronous. You cannot simply make childs variable global and use it anywhere you want in your class. This is happening because onDataChange() method is called even before you are getting the data from the database. For a better understanding, please see my answer from this post.

For a quick fix, just use the value of your childs variable, only inside the onDataChange() method.

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