Alexandre Ouimet
Alexandre Ouimet

Reputation: 25

How to retrieve data on firebase firestore Android?

I have been searching for quite a while now and I can't seem to find anything to help me...

I want to fetch data from a firebase firestore collection that I have in reference (timeEntryTable). In the debugger, I can see that my data is accessed correctly, but when I get out of the method, it seems like everything is gone...

private void getTimes(){
        float totalTime = 0;

        timeEntryTable
                .whereEqualTo("person", "Alexandre")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {

                                TimeEntry timeEntry = new TimeEntry(document.getData());
                                times.add(timeEntry.getTime());

                                Log.d(TAG, document.getId() + " => " + document.getData());
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
        System.out.println("times = " + times);
    }

In this snippet, times is a private ArrayList member and TimeEntry is a POJO that has the structure of the documents in the collection.

I can really see in the debugger that times is filled with the right data, but when I call System.out.println("times = " + times);, the value is []... Is there something I am not doing correctly?

Thank you :)

Upvotes: 0

Views: 135

Answers (2)

Rajeevan
Rajeevan

Reputation: 150

To add to the previous answer that "the first time you can use the results is inside the callback itself", move the "System.out.println("times = " + times);" line right outside underneath your for loop.

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317427

Firestore's get() operation, and all of its APIs, are asynchronous and return immediately, before the data is available. Your code continues to execute while the query completes. Some time later, the callback you attached with addOnCompleteListener will be invoked with the results of the query.

The first time you can use the results is inside the callback itself. You can't be certain that any other access to your times array will contain anything. This means that you will have to build your program around these asynchronous APIs instead of depending on line-by-line execution.

Upvotes: 0

Related Questions