Simone
Simone

Reputation: 1

Android firebase count element

I want to count elements in a firebase database, I have seen different topics and tried this code:

final Query dataQuery = myRef.equalTo(MainActivity.user.getUid()).getRef();
    dataQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.e("ERROR",""+dataSnapshot.child(MainActivity.user.getUid()).getChildrenCount());

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e(TAG, "onCancelled", databaseError.toException());
        }
    });

Now, the value in log error is correct but, if I try to assign it in field, or static field is always 0 out of this method; How can I use this value in other class?

Upvotes: 0

Views: 262

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138834

You cannot simply take that value and use it outside onDataChange() method, because it will always be null. This is happening because this method has an asynchronous behaviour, which means that is called even before you are getting the data out from the database. A quick fix would be to use that value only inside onDataChange() method, or to dive into the asynchronous world and see the last part of my answer from this post.

Upvotes: 1

dazza5000
dazza5000

Reputation: 7628

You need to use a callback and call a method on the callback in your onDataChange. Then once that callback is returned you can continue with the rest of your logic.

You can see an example of that here:

https://github.com/Austin-Android/austin-feeds-me/blob/master/app/src/main/java/com/austindroids/austinfeedsme/data/firebase/FirebaseEventsDataSource.java#L40

fireBase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Event event = snapshot.getValue(Event.class);
                events.add(event);
            }
            callback.onEventsLoaded(events);
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {

        }
    });

Upvotes: 1

Related Questions