1

After create data on Firebase. I try retrieving data from Firebase. But I have problem, I think may be Log.d(TAG,list.size()) run before ref.addChildEventListener(childEventListener); complete. Who can help me ?

public class NewFirebase extends AppCompatActivity {

    List < Product > list = new ArrayList < > ();
    private static final String TAG = "Firebase";
    DatabaseReference ref;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Firebase.setAndroidContext(this);
        ref = FirebaseDatabase.getInstance().getReference();
        ChildEventListener childEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
                Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());

                // A new comment has been added, add it to the displayed list
                Product comment = dataSnapshot.getValue(Product.class);
                for (DataSnapshot child: dataSnapshot.getChildren()) {
                    Product post = child.getValue(Product.class);
                    list.add(post);
                }
                // ...
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
                Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
                Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "postComments:onCancelled", databaseError.toException());

            }
        };
        ref.addChildEventListener(childEventListener);
        Log.d(TAG, list.size() + "");
    }

    class RetrievingData extends AsyncTask < Void, Void, Void > {

        @Override
        protected Void doInBackground(Void...voids) {

            return null;

        }
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
TungLoGach
  • 51
  • 1
  • 13
  • yes `Log.d(TAG,list.size()) run before ref.addChildEventListener(childEventListener); complete` but what do you want next – Linh Oct 04 '16 at 02:12
  • That data is loaded asynchronously, so it may take some time before it becomes available to your app's code. You can't return something *now*, that hasn't loaded yet. See this Q&A for a good explanation of asynchronous behavior: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Frank van Puffelen Oct 04 '16 at 02:19
  • I want ref.addChildEventListener(childEventListener); complete before Log.d(TAG, list.size()) run. – TungLoGach Oct 04 '16 at 02:21

2 Answers2

1

You need to take a second approach to how you are structuring your code, or even take a look at the definition of callback/listener itself.

The addChildEventListener() method assigns a callback and initiates a query for retrieving the result. That is, of course, done in background.

Using listeners will never work that way, that's why they were made for, to don't follow line-by-line execution. If you want to get some result from them, you need to put the code inside their methods, which is when they give you some response. Can take milliseconds, seconds, even minutes, but don't expect to be so immediate to be quicker than the execution of the next line that it was posted to execution.

Sergio Carneiro
  • 3,726
  • 4
  • 35
  • 51
1

Take a look at https://www.firebase.com/docs/android/guide/retrieving-data.html.
If you want to see the size of the list that you get from Firebase database, you should use addValueEventListener instead of addChildEventListener

List<Product> commentList = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot snapshot) {
        for (DataSnapshot postSnapshot: snapshot.getChildren()) {
            Product comment = postSnapshot.getValue(Product.class);
            commentList.add(comment);
        }
        // here you can print the size of your list
        Log.d(TAG,list.size())
    }

    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
});
Linh
  • 57,942
  • 23
  • 262
  • 279