0
Integer scores[] = new Integer[10];
int count = 0;

I have some data that I want to put into array. I put it in onChildAdded, but if I need to get the data from the array out of the onChildAdded, console shows "null".

If I will try to get the data of array into onChildAdded, it will be success

data.child("scores").addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        count++;
                        scores[count] = dataSnapshot.getValue(Integer.class);
                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

int i = scores[1];

IMPORTANT MOMENT

For example, If I will use operation FOR

for (int i = 0; i < 10; ++i) {
        scores[i] = i;
    }

    int i = scores[3];

i will not be null

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Shyngys Rakhad
  • 196
  • 2
  • 4
  • 16
  • Has the `onChildAdded` method already been called when you get the data out of the array? – JensV Mar 19 '19 at 13:41

1 Answers1

2

Firebase APIs are asynchronous, meaning that each one of those methods: onChildAdded(), onChildChanged() etc, return immediately after it's invoked, and the callback from the Task it returns, will be called some time later. There are no guarantees about how long it will take. So it may take from a few hundred milliseconds to a few seconds before that data is available. Because that method returns immediately, the scores array has not have been populated from the callback yet and that's why is empty.

Basically, you're trying to use a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.

A quick solve for this problem would be to move the following lines of code:

for (int i = 0; i < 10; ++i) {
    scores[i] = i;
}
int i = scores[3];

Inside the onChildAdded() method, where the data is available.

If you need to loop your score array outside the callback, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

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