未在arrayList中添加项目

时间:2018-09-06 19:03:56

标签: android firebase arraylist google-cloud-firestore

我使用Firebase Firestore存储一些数据。我将数据存储在TimeForm活动中。

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
globalClass.setAction(actionText);
globalClass.setTime(totalTime);
globalClass.setUser_email(user.getEmail());
ScheduleClass scheduleClass = new ScheduleClass(fromEditText.getText().toString() + " - " + untilEditText.getText().toString(), multiLineEditText.getText().toString(), user.getEmail());
Map<String, Object> userMap = new HashMap<>();
userMap.put("Time", globalClass.getTime());
userMap.put("Action", globalClass.getAction());
userMap.put("user_email", globalClass.getUser_email());
mondayCollectionReference = db.collection("Monday");
tuesdayCollectionReference = db.collection("Tuesday");                                                      
mondayCollectionReference.document().set(userMap, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Toast.makeText(TimeForm.this, "Submitted", Toast.LENGTH_SHORT).show();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("ERROR", e.getMessage());
        }
    });

一切在这里都能正常工作,数据以我想要的格式存储。然后,我在MainActivity检索数据。因此,在TimeForm中,用户添加的时间类似15:00-17:00,但是他添加了多个时间,在MainActivity中,我将所有时间存储在ArrayList中。这是代码:

db = FirebaseFirestore.getInstance();
final ArrayList<String> loadMondayTimeArrayList = new ArrayList<>();
user = FirebaseAuth.getInstance().getCurrentUser();
db.collection("Monday").addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(@Nullable QuerySnapshot documentSnapshots, @Nullable FirebaseFirestoreException e) {
        for(DocumentSnapshot documentSnapshot : documentSnapshots){
            String time;
            String action;
            String user_email;
            time = documentSnapshot.getString("Time");
            action = documentSnapshot.getString("Action");
            user_email = documentSnapshot.getString("user_email");
            mondayTimeArrayList.add(time);
        }
    }
});

当我在addSnapShotListener中记录时间时,它会完美记录时间。但是,当我将时间添加到mondayTimeArrayList并尝试在addSnapShotListener之外记录mondayTimeArrayList的项目时,出现“索引超出范围”错误。

1 个答案:

答案 0 :(得分:1)

这是因为添加快照侦听器是异步的,并且该方法立即返回。直到调用回调并成功完成回调时,才会填充您的数组。如果要使用侦听器的结果,则只有在侦听器完全完成后才能访问它们。