0

As on the below code, I was trying to iteratively get the "AVG" value from a Firebase collection document. But this code will loop only till addOnCompleteListener, so it's not populating the updatedYears array.

Basically what I need to do is, I have two drop-downs, Based on the 1st drop-down selection, the 2nd drop-down value needs to be changed by getting the data from the Firebase database.

public void getYearList(String type) {

    for (String year:allYearList) {

        int i = 0;
        DocumentReference docref = FirebaseFirestore.getInstance().collection(type).document("2016");
        docref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                DocumentSnapshot doc = task.getResult();
                updatedYears[i] = doc.get("Avg").toString();
                
            }

        });
    }
}

I was calling this method from the setOnItemSelectedListener by the 1st dropdown.

spinner = (Spinner)findViewById(R.id.spinner);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,paths);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
    
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                    getYearList(spinner.getSelectedItem().toString());
    
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> parentView) {
                    // your code here
                }
    
            });
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
user2728409
  • 245
  • 4
  • 15
  • Are you saying your `onComplete` is not getting called? If you put a breakpoint on `task.getResult()` and run in a debugger, does it not reach that line? – Frank van Puffelen Dec 29 '21 at 17:44
  • Based on the [documentation](https://firebase.google.com/docs/firestore/query-data/get-data#java_2), the [`Task`](https://developers.google.com/android/reference/com/google/android/gms/tasks/Task) that is executed should either succeed or fail after it completes, so your code should handle both cases. Since your array is not being populated, your task could be failing in some way. If you add the code to check for failures, you could receive more details about why you are not getting data. You can also check this [related](https://stackoverflow.com/questions/69954430/) question for reference. – ErnestoC Dec 29 '21 at 23:05
  • If your `onComplete` fires, have you checked what happens if the Task is not successful? – Alex Mamo Dec 30 '21 at 10:24

0 Answers0