Currently, I'm building an Android App which is using a Firebase Database.
In my code, I'm trying to get the number of Children in a specific path of my Firebase Database. Having defined the reference of the Firebase specific path, I have made a Listener in order to get the DataSnapshot and then to call getChildrenCount().
After that, I want to use this result in a FOR-Loop. However, the code doesn't work.
It appears that it is executed first the FOR-Loop (I realised that because Log.v("NUM_OF_PRODUCTS",numOfProducts+"") outputs 0 insteed of 3) and the Listener is executed after, while in the code, listener code comes first and FOR-Loop code next. 
Part of my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_product_selection);
    selected_cat = getIntent().getExtras().getString("pass_selected_cat");
    listView = (ListView) findViewById(R.id.listView);
    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
    listView.setAdapter(adapter);
    fbdatabase = FirebaseDatabase.getInstance();
    fbref_products = fbdatabase.getReference("PRODUCTS/SM_0/" + selected_cat);
    //Listener for getting numOfProducts.
    fbref_products.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            numOfProducts = (int) dataSnapshot.getChildrenCount();
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    //Print numOfProducts before FOR-Loop being executed.
    Log.v("NUM_OF_PRODUCTS",numOfProducts+"");
    //FOR-Loop 
    for (int i = 0; i < numOfProducts; i++) {
        String str = i + "";
        DatabaseReference product_ref = fbref_products.child(str);
        product_ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                String productName = (String) map.get("productName");
                arrayList.add(productName);
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                //textView.setText("The read failed: " + databaseError.getMessage());
            }
        });
    }
My code works fine if instead the variable numOfProducts, we had a specific number.
Could anyone help me??
 
     
    