离线android应用期间如何在Firestore中添加检测数据 [英] How to detect data is added in firestore during offline android app

查看:65
本文介绍了离线android应用期间如何在Firestore中添加检测数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Android中的Firestore.我想允许我的用户在脱机模式下将数据保存在应用中.(脱机期间的数据插入也可以正常工作)但是我不知道如何检测到在脱机模式下添加了数据,我需要获取文档添加的ID.在联机模式下,我可以使用侦听器as来检测数据插入.

I'm working with firestore in android. I want to allow my user to save the data in app during the offline mode.(Data insertion during offline is also working fine) But I don't know how I can detect that data is added in offline mode, I need to get document id that is added. In the online mode I can detect the data insertion with the listener as.

Map<String, Object> data = new HashMap<>();
data.put("name", "Tokyo");
data.put("country", "Japan");

db.collection("cities")
        .add(data)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

我还需要检测应用程序离线时添加的内容.那我该怎么办?因为这些侦听器仅在将数据插入服务器中并且应用程序从服务器获得响应时才起作用.

I also need to detect that is added when the app is offline. So how I can? Because these listeners only works when the data is inserted in the server and app get the response from the server.

推荐答案

只有将数据提交到服务器后,才会调用 addOnSuccessListener .这是其明确的目标.如果本地客户端在将数据添加到本地后还需要数据,则可以使用常规的 addSnapshotListener 来实现.

The addOnSuccessListener only gets called once the data is committed to the server. That's its explicit goal. If you local client also need the data after it's added locally, you'll do that with a regular addSnapshotListener.

有关本地更改事件的文档中:

应用程序中的本地写入将立即调用快照侦听器.这是由于称为等待时间补偿"的重要特征.当您执行写操作时,将在数据发送到后端之前在 通知您的侦听器.

检索到的文档具有 metadata.hasPendingWrites 属性,该属性指示文档是否具有尚未写入后端的本地更改.您可以使用此属性来确定快照侦听器接收到的事件的来源.

Retrieved documents have a metadata.hasPendingWrites property that indicates whether the document has local changes that haven't been written to the backend yet. You can use this property to determine the source of events received by your snapshot listener.

有关如何处理此示例代码,请参见链接的文档.

See the linked documentation for sample code of how to process this.

更新:如果您只是想获取新文档的ID,则只需执行以下操作即可:

Update: if you're just trying to get the ID of a new document, you can simply do:

DocumentReference newDoc = db.collection("cities").document();
System.out.println(newDoc.getId());
newDoc.set(data);

请参见 CollectionReference.document() .

这篇关于离线android应用期间如何在Firestore中添加检测数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆