首页 > 解决方案 > Android firestore 云函数 SnapshotListener 更新缓存并获取最新文档的字段

问题描述

用户在诊所预约。我想获取最后一个用户的预约时间,该时间位于我的 firestore 数据库的顶部文档中。我能够得到它,但是如果我删除顶部文档并进行另一次约会,它将使用已删除文档的时间而不是新的顶部文档。如果有更好的方法请分享。

    Collection col = firestore.collection("Clinic Name");

    //Get 1 document the top one

    Query query = col.orderBy("Time",Query.Direction.DESCENDING).limit(1);
      query.addSnapshotListener(MetadataChanges.INCLUDE, new 
      EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots,
                            @javax.annotation.Nullable FirebaseFirestoreException e) {
            if (e != null) {

                return;
            }
            if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {

              for (DocumentSnapshot dc : queryDocumentSnapshots) {

                String prevTime = dc.getString("Time");

                //Add the data
                AddAppointment(prevTime);

           }

      }  


     //Function that add the data
     void AddAppointment(String time){
         if(time.isEmpty){
            time = "08:00:00";
          }
         LocalTime localTime = LocalTime.parse(time);
        localTime =  String.valueOf(localTime.plusMinutes(8));

       Map<String, Object> data = new HashMap<>();
       data.put("Time",localTime);
       //more data ... 

      //Adding the document
      firebase.collection("ClinicName").document("userId").set(data)...
      }

标签: javaandroidgoogle-cloud-firestoregoogle-cloud-datastoregoogle-cloud-functions

解决方案


推荐阅读