0

I can read data in for loop but when I return the list its null in all cases I try. Please help me to get the list callback from function. Thank you all!

    List<TableModel> list;
    public List<TableModel>  getAllTable()
    {
        list = new ArrayList<>();
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                DataSnapshot dataSnapshot = snapshot.child("Ban");
                for (DataSnapshot valueTable : dataSnapshot.getChildren()) {
                    TableModel tableModel = valueTable.getValue(TableModel.class);
                    Log.d("checktenban",tableModel.getTenBan());
                    
                    list.add(tableModel);
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        };
        nodeRoot.addListenerForSingleValueEvent(valueEventListener);
        Log.d("size of list", String.valueOf(list.size()));
        return list;
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Data is loaded from Firebase asynchronously. Since they may take some time, your main code continues while the data is being loaded, and then your `onDataChange` is called once the data is available. This means that your `return list;` (and the `Log.d` above it) run **before** the `list.add(tableModel);` is ever called. --- Any code that needs access to the data from the database needs to be inside `onDataChange` or be called from there. This also means you can't return such data to the caller. For more on this and examples, see https://stackoverflow.com/q/50434836 – Frank van Puffelen Oct 22 '20 at 13:32
  • Thank you Sir , I almost understand. Before, I misread that database on Firebase realtime similar to SQLite that we can get return at the same time. However, now I can change this function avoiding null return – Thành Tâm Cao Oct 22 '20 at 14:58

0 Answers0