考虑下面的代码示例:
// 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父项目?
发布于 2016-04-08 06:26:04
由于您只检索了子项,因此DataSnapshot不包含父项的数据。但在ref上可以很容易地访问它。
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
ref.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot parent) {
System.out.println("Got parent");
}
...
});
}发布于 2020-03-31 16:18:06
我知道这个帖子已经很老了,但下面是对我有用的
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
DatabaseReference parent = dataSnapshot.getRef().getParent();
if( parent != null){
String parentNode = parent.getKey();
}
}因此,基本上在Datasnapshot上调用.getRef()、.getParent()、.getKey()就可以了。
https://stackoverflow.com/questions/36485171
复制相似问题