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
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);
}