gpt4 book ai didi

java - 当 onChildAdded 事件被触发时,如何在 Firebase 中获取父项?

转载 作者:行者123 更新时间:2023-12-02 03:44:16 24 4
gpt4 key购买 nike

考虑以下代码示例:

// Get a reference to our posts
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
ref.addChildEventListener(new ChildEventListener() {
// Retrieve new posts as they are added to the database
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
BlogPost newPost = snapshot.getValue(BlogPost.class);
System.out.println("Author: " + newPost.getAuthor());
System.out.println("Title: " + newPost.getTitle());
}
//... ChildEventListener also defines onChildChanged, onChildRemoved,
// onChildMoved and onCanceled, covered in later sections.
});

触发 onChildAdded 时是否可以在 Firebase 中获取 DataSnapshot 父项?

最佳答案

由于您只检索了子项,因此 DataSnapshot 不包含父项的数据。但可以通过 ref 轻松访问它。

public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
ref.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot parent) {
System.out.println("Got parent");
}
...
});
}

关于java - 当 onChildAdded 事件被触发时,如何在 Firebase 中获取父项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com