【问题标题】:Adding new item at 0 position in firestore?在firestore的0位置添加新项目?
【发布时间】:2019-05-28 21:16:43
【问题描述】:
mFirestore.collection("notifications").orderBy("timestamp",Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>(){
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot documentSnapshots,@javax.annotation.Nullable FirebaseFirestoreException e){
        if(e!=null){
        Log.d(TAG,"Error : "+e.getMessage());
        }

        assert documentSnapshots!=null;

        for(DocumentChange doc:documentSnapshots.getDocumentChanges()){

        if(doc.getType()==DocumentChange.Type.ADDED){
        String doc_id=doc.getDocument().getId();
        NotificationModel Notifications=doc.getDocument().toObject(NotificationModel.class).withDocId(doc_id);
        allNotifications.add(Notifications);
        notificationAdapter.notifyDataSetChanged();

        }
        }
        }
        });

我正在尝试这样做,当在 Firestore 集合中添加一个新文档时,它将添加到 0 位置。但不是 0 位置,而是在最后一个位置添加一个新项目。

【问题讨论】:

    标签: java android firebase android-studio google-cloud-firestore


    【解决方案1】:

    firestore 集合中的文档不存储为数组,而是以地图方式存储,这意味着您不能在特定位置插入文档

    你可以看这里https://firebase.google.com/docs/firestore/data-model

    【讨论】:

      【解决方案2】:

      要解决这个问题,请更改以下代码行

      allNotifications.add(Notifications);
      

      allNotifications.add(0, Notifications);
      

      根据官方文档关于ArrayList的add()方法:

      在此列表中的指定位置插入指定元素。

      【讨论】:

        【解决方案3】:

        我通过更改 allNotifications.add(Notifications); 来解决我的查询

        到这个allNotifications.add(doc.getNewIndex(),Notifications);

        【讨论】:

          猜你喜欢
          • 2016-08-24
          • 1970-01-01
          • 2018-09-16
          • 1970-01-01
          • 1970-01-01
          • 2018-04-29
          • 2021-02-08
          • 1970-01-01
          • 2022-01-09
          相关资源
          最近更新 更多