0

I am using the below code to retrieve and store the number of children to a variable. I want to retrieve the number of children, save it in a variable and then put it in a HashMap alongside other variables to update a record.

 usersRef.addValueEventListener(new ValueEventListener() {
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                no[0] = (int) dataSnapshot.getChildrenCount();
                                if (no[0] <= 0)
                                {
                                    number[0] = "0000";
                                    childCount = number[0];
                                }
                                else
                                {
                                    number[0] = String.format("%04d", no[0]).substring(0,4);
                                    childCount = number[0];
                                }
                                usersRef.addListenerForSingleValueEvent();
                                System.out.println("In onDataChange, count="+ number[0]);
                            }
                            public void onCancelled(DatabaseError databaseError) { }
                        });
                        System.out.println("After adding listener, count="+ number[0]);

Problem is childCount, even though it is a global variable, is getting a value inside the onDataChange but not after it. I have tried all the solutions I could find on Stack Overflow and still nothing. What am I doing wrong?

James Ele
  • 43
  • 6
  • Firebase API is asynchronous, so there is no way you can use the value of `number[0]` outside the onDataChange. So please check the duplicate to see how can you solve this using a custom callback. – Alex Mamo May 13 '21 at 10:33
  • Thank you for helping out. I guess I was searching the wrong thing. Should I remove the question? – James Ele May 13 '21 at 10:34

0 Answers0