I am trying to access some data from a Firestore collection. I am then trying to return that array of transactions. However I am unable to do this because of the OnComplete method.
public ArrayList<Transaction> getTransactions(){
//initializing firebase auth object
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
//Establishing database connection
db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection("users").document(currentUser.getEmail());
//this is the array I am trying to return.
ArrayList<Transaction> trans = new ArrayList<>();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
//update the array with the data received.
trans = (ArrayList<Transaction>) document.getData().get("transactions");
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
return trans;
}
The returned output is an empty list because the onComplete method is being triggered after the getTransactions() returns.