0

I'm facing a situation where I want to retrieve field values(timings) and store them in sorted order in an ArrayList to process them later on. There are 24 values in my document(00-23). I want to store values at indexes in ascending order as the loop iterates e.g. Value of 00 should be stored at timesList(0) and 23 should be stored at timesList(23). But loop runs much faster than firebase code and I am receiving values in a disordered manner.

final DocumentReference docRef = db.collection("parent").document(child);
        docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {

                  for(int tcounter=0;tcounter<24;tcounter++){
                      if(tcounter<10){
                          documentSnapshot.getString("0"+String.valueOf(tcounter)); 
                          timesList.add(documentSnapshot.getString("0"+String.valueOf(tcounter))); 
                      }
                      else{
                          documentSnapshot.getString(String.valueOf(tcounter));
                          timesList.add(documentSnapshot.getString(String.valueOf(tcounter)));
                          if(tcounter==23){
                              valuesdownloaded="yes";
                          }
                      }

                }
             }
        });

My Firebase document format

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Saqeeb
  • 113
  • 6

1 Answers1

0

Not necessarily the solution to your problem, but this code is a lot shorter and does the same as what you currently do:

final DocumentReference docRef = db.collection("parent").document(child);
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        for(int tcounter=0;tcounter<23;tcounter++){
            String key = (tcounter<10) ? "0"+String.valueOf(tcounter) : String.valueOf(tcounter);
            timesList.add(documentSnapshot.getString(key)); 
        }
        valuesdownloaded="yes";
     }
});

Aside from that, I have a suspicion that you're doing something based on the value of valuesdownloaded. You'll want to note that data is loaded from Firebase asynchronously, and any code that requires data from the database should be inside the onSuccess or be called from there. See my longer explanation here for an example: How to check a certain data already exists in firestore or not

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807