java - 火力地堡 : Firestore : What is the equivalent of ChildEventListener found in Realtime Database

标签 java android firebase firebase-realtime-database google-cloud-firestore

我有这个用于 Firestore。

FirebaseFirestore   db  = FirebaseFirestore.getInstance();
        CollectionReference ref = db.collection("app/appdata/notifications");
        ref.addSnapshotListener((snapshot, e) -> {
            if (e != null) {
                Log.w(TAG, "Listen failed.", e);
                return;
            }

            for (DocumentSnapshot x : snapshot.getDocuments()) {
                System.out.println(x.getData());
            }
        });

但我不想使用那个循环,相反我只需要获取新的 child 。我想要在 Realtime Db 中看到的类似以下内容。

ref.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
        Post newPost = dataSnapshot.getValue(Post.class);
        System.out.println("Author: " + newPost.author);
        System.out.println("Title: " + newPost.title);
        System.out.println("Previous Post ID: " + prevChildKey);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {}

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});

最佳答案

您需要在 QuerySnapshot 对象上使用 .getDocumentChanges() 来获取自上次快照以来的更改列表。这相当于实时数据库中的子更改事件。例如:

FirebaseFirestore   db  = FirebaseFirestore.getInstance();
CollectionReference ref = db.collection("app/appdata/notifications");
ref.addSnapshotListener((snapshot, e) -> {
    if (e != null) {
        Log.w(TAG, "Listen failed.", e);
        return;
    }

    for (DocumentChange dc : snapshots.getDocumentChanges()) {
        switch (dc.getType()) {
            case ADDED:
                // handle added documents...
                break;
            case MODIFIED:
                // handle modified documents...
                break;
            case REMOVED:
                // handle removed documents...
                break;
            }
        }
    }
});

参见 https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots了解更多详情。

关于java - 火力地堡 : Firestore : What is the equivalent of ChildEventListener found in Realtime Database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46640643/

相关文章:

java - Enum 不能与 for switch 语句一起使用

android - CMake 错误 : Could not create named generator Android Gradle - Ninja

android - Firebase 数据库权限被拒绝,读/写权限设置为 true

android - Firebase isSuccessful() 总是返回 false

Android firebase 推送通知最低版本问题

javascript - Firebase 函数如何在循环完成迭代后发送

android - FirebaseRemoteConfig : Cannot resolve symbol

java - 跨多个进程均匀分布数据库记录

java - 在 Spring 应用程序中从 JBOSS 4.2.3 配置 JNDI 数据源

java - 抛出 BadRequestException(ResponseEntity) 与捕获错误,返回 ResponseEntity(HTTPStatus.BadRequest) ReST API