android - 如何检测数据在离线 Android 应用程序期间添加到 firestore

标签 android firebase google-cloud-firestore

我在 android 中使用 firestore。我想让我的用户在离线模式下将数据保存在应用程序中。(离线期间的数据插入也可以正常工作)但是我不知道如何检测到在离线模式下添加了数据,我需要获取文档添加的id。在在线模式下,我可以使用监听器检测数据插入。

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

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

最佳答案

addOnSuccessListener 只有在数据提交到服务器后才会被调用。这是它的明确目标。如果您的本地客户端在本地添加数据后还需要数据,您可以使用常规的 addSnapshotListener 来完成。

来自documentation on events for local changes :

Local writes in your app will invoke snapshot listeners immediately. This is because of an important feature called "latency compensation." When you perform a write, your listeners will be notified with the new data before the data is sent to the backend.

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.

有关如何处理此问题的示例代码,请参阅链接文档。

更新:如果您只是想获取新文档的 ID,您可以简单地执行以下操作:

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

参见 CollectionReference.document() .

关于android - 如何检测数据在离线 Android 应用程序期间添加到 firestore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51004571/

相关文章:

android - 9.6.0 库中的 Firebase proguard 错误

javascript - Angularfire 增量交易

javascript - 如何获取 Firebase 数据库集合中文档的唯一 ID(键)?

android - Gridview 中的小部件在屏幕外时丢失状态

java - 启动画面中的线程

Android Studio错误: “Environment variable does not point to a valid JVM installation”

javascript - 获取 Firebase 集合中的所有文档 - React

java - 以编程方式在 Java/Android 中进行 Saxon XSLT 转换

android - 无法从 firebase 存储中检索图像

ios - JSON 到 iOS 的子弹形式数据