0

i want to count all child from a Firebase Realtime Database:

int iLinesF = 0;
myRef = null;
if (myRef == null) {
    myRef = FirebaseDatabase.getInstance().getReference();
    }
    myRef.child("users")
        .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            iLinesF = (int) snapshot.getChildrenCount();
            Toast.makeText(MainActivity.this,String.valueOf(iLinesF),Toast.LENGTH_SHORT).show();// #1
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
    Toast.makeText(MainActivity.this,String.valueOf(iLinesF),Toast.LENGTH_SHORT).show(); //#2

Why the second Toast appears first? Why the value in the first Toast is right and in the second 0?

Thanks, dplusk

Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
dplusk
  • 11
  • 3
  • That's a classic asynchronous problem. You can't simply use the value of `iLinesF` outside the callback. Please check the duplicate to see how you can solve this. – Alex Mamo Oct 04 '21 at 11:41

0 Answers0