0

I have this code:

DocumentReference documentReference = fStore.collection("Studenti").document(userID);
    documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {

        @Override
        public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {

            View header = navigationView.getHeaderView(0);
            TextView text = header.findViewById(R.id.nume_elev);

            //text.setText(documentSnapshot.getString("nume"));
            //String mail = documentSnapshot.getString("email");

            spec = documentSnapshot.getString("specializare"); // it gets the value from firebase


        }
    });


    //Query
    Query qexamene = fStore.collection("/Examene/an1/sem1").whereEqualTo("specializare", spec); 

How can I use 'spec' or the "documentSnapshot.getString" outside of onEvent method?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 2
    Store it in a member variable or global, and make sure the other code doesn't execute until after the callback is invoked asynchronously. Or, pass the data along to a method that you invoke from within the callback. – Doug Stevenson Jul 05 '20 at 21:27
  • can you please go into a bit more detail or point me to a place where I could understand this? I'm new to android studio and programming in general. – Enachescu Claudiu Jul 05 '20 at 21:31
  • I tried to have 'spec' as a String var but it doesn't help, when it gets out of onEvent it loses the value assigned in the onEvent method. I don't know how to code to use it in the line below. – Enachescu Claudiu Jul 05 '20 at 21:34
  • That's because addSnapshotListener is asynchronous, and the callback you provide will be invoked some time later, after the query completes. You will need to use the callback to continue your work. – Doug Stevenson Jul 05 '20 at 21:38
  • All code that needs the data from the database, needs to be inside `onEvent` or be called from there. I added some links to previous questions covering the same. This one specifically deals with nested queries: https://stackoverflow.com/questions/61542953/how-to-assign-field-value-of-a-collection-document-to-another-collection-documen/61543603#61543603 – Frank van Puffelen Jul 05 '20 at 21:49

0 Answers0