简体   繁体   中英

Firebase: Loop on dataSnapshot executes only once

The following is my Firebase database graph:

在此处输入图像描述

There are three children of the root element links . When I execute the following loop to get all children, it returns the result for only the first child

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("links");
        int count=0;


        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {


            Log.d("Firebase","Children: "+dataSnapshot.getChildren().toString());    //This gives result for all children

                for (DataSnapshot ds : dataSnapshot.getChildren()) {

                    count++;
                }
                Log.d("Firebase","Count length: "+count);     //Gives only "1"
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });

In the above code the count should be 3 but it returns 1. The loop executes only once. However the following line in the above code works correctly and gives results for all 3 children.

Log.d("Firebase","Children: "+dataSnapshot.getChildren().toString());

Where is the problem? Thanks for your answers!

If you want to get the number of children under links , then try the following:

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.d("Firebase","Children: "+dataSnapshot.getChildren().toString()); //This gives result for all children
        long childCount = dataSnapshot.getChildrenCount();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
});

getChildrenCount() will return then number of direct children under links , in this case 3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM