0

I want to read data from firestore and store "amount" field in array so that I can show it in ListView or TableView. I created ArrayList and added all amounts in it then when I print them I got empty ArrayList, however if I print them in "onComplete" method then it's showing correct output.

my "amount" field is in "transactions" field, see below image

Firestore Image

My code:

public class ShowTransactionHistory extends AppCompatActivity {

FirebaseFirestore db = FirebaseFirestore.getInstance();
ArrayList<Long> amounts = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_transaction_history);
DocumentReference docRef = db.collection("Pocket Money").document(MainActivity.ID);
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    Map<String, Object> map = document.getData();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        if (entry.getKey().equals("transactions")) {
                            List transactions = (List) document.get("transactions");
                            for (Object transaction: transactions) {
                                Map values = (Map)transaction;
                                long amount = Long.parseLong(values.get("amount").toString());
                                amounts.add(amount);
                            }
                        }
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "No such document!", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_LONG).show();
            }

        }
    });
    
    System.out.println("-----------------------------");
    System.out.println(amounts);
}
User
  • 21
  • 5
  • There is no way you can use the value of `amounts` outside the onComplete method. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this article, [How to read data from Cloud Firestore using get()?](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953). – Alex Mamo Dec 18 '21 at 09:17

0 Answers0