0

im quiet new in firebase database and android, I am create a method to count total size of db children, but it always return 0 when accessed outside onDataChange method, here my code

private int getChildSize() {
 final List<String> keys = new ArrayList<>();
 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("profiles");
    ref.orderByChild("phoneNumber")
            .equalTo(phoneNumber)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot item : dataSnapshot.getChildren()){
                        keys.add(item.getKey());

                        Log.d(TAG, "onDataChange: " + keys.size()); // more than 0
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

 return keys.size(); // return 0;
}

any ideas?

Gusti Arya
  • 1,281
  • 3
  • 15
  • 32

2 Answers2

1

Firebase calls are async, so you need the result to come back entierely before you can return it. What you can do is to call a method when the calll finishes:

private void getChildSize() {
 final List<String> keys = new ArrayList<>();
 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("profiles");
    ref.orderByChild("phoneNumber")
            .equalTo(phoneNumber)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot item : dataSnapshot.getChildren()){
                        keys.add(item.getKey());

                        Log.d(TAG, "onDataChange: " + keys.size()); // more than 0
                    }
                    finishedCounting(keys.size())

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

}

public void finishedCounting(int size){
//do something with size
}
Levi Moreira
  • 11,917
  • 4
  • 32
  • 46
0

Split that function:

put your ValueEventListener into a separate init function which does have no return type(void).

and make getChildSize function only return the size.

Since your ValueEventListener is async it does not assign any values before the return statement is called.

Maksym V.
  • 2,877
  • 17
  • 27