0

I am trying to retrieve the value of year from a collection on cloud firestore, I will use this year value to retrieve data from the firestore storage. The code I am using for doing this is

        DocumentReference documentReference = fStore.collection("Users").document(userId);
        documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                if (error != null){

                    if (progressDialog.isShowing())
                        progressDialog.dismiss();
                    Log.e("Firestore error",error.getMessage());
                    return;
                }
                assert value != null;
                String gyear = value.getString("Year");
                setYear(gyear);
            }
        });
       storageReference = FirebaseStorage.getInstance().getReference("AcademicCalendar/"+getYear()+"/AC.jpg");

here the setYear and getYear are setter and getter for the year variable of type string. I want to store the value of year from firestore to this string. But when I do so I am getting the value as null. Below I have printed the storageReference, as you can see the value is null.

I/System.out: StorageRefgs://dsu-app-cm.appspot.com/AcademicCalendar/null/AC.jpg

could your please help me find a way to store the year in a string variable so I can use it to retrieve data from firebase storage?

  • Have you checked the Firestore documentation for reading data? https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document – Todor Kostov Nov 28 '21 at 16:41
  • 1
    Data is loaded from Firestore (and most modern cloud APIs) asynchronously. If you step through this code in a debugger, or place some log statements, you'll see that your `storageReference = FirebaseStorage.getInstance()...` happens *before* the call to `setYear(gyear)` ever executes, which is why you don't get the value you expect. The solution for this is always the same: any code that needs the data from the database must be inside `onEvent` or be called from there. – Frank van Puffelen Nov 28 '21 at 18:22

0 Answers0