In my RegistrationActivity.java class file I've declared a numOfUsers variable to count the number of users in my database.
import ...
public class RegistrationActivity extends AppCompatActivity {
   //Other declarations
    private static long numOfUsers;
I've created an event listener for checking if a particular user exists in the database. Inside this event listener there is another event listener which counts the total number of users in the database.
        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(!dataSnapshot.exists()) {
                    //create new user
                    database.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            if (dataSnapshot.exists()) {
                                numOfUsers = dataSnapshot.getChildrenCount();
                               
                            }
                        }
                      
                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {
                        }
                    });
//Displaying the numOfUsers in app
                    userinfo.setText(String.valueOf(numOfUsers));
                }
This prints 0. If I place userinfo.setText(String.valueOf(numOfUsers)); inside the second event listener then everything works fine.
        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(!dataSnapshot.exists()) {
                    //create new user
                    database.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            if (dataSnapshot.exists()) {
                                numOfUsers = dataSnapshot.getChildrenCount();
//This works perfectly fine
                                userinfo.setText(String.valueOf(numOfUsers));
                               
                            }
                        }
                      
                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {
                        }
                    });
                  
                }
I don't understand why this is happening. numOfUsers is a static class variable I should be able to access it's value from anywhere inside the class. Is there a way I can't print numOfUsers outside the second event listener?
