如何在触发onChildAdded事件时获取Firebase中的父项?

时间:2016-04-07 19:13:15

标签: java android firebase

考虑以下代码示例:

// 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父项?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

我知道这个线程已经很老了,但这是对我有用的

@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()即可完成工作。