How to get the parent item in Firebase when onChildAdded event is triggered?

Considering the following code example:

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

Is it possible to get DataSnapshot parent item in Firebase when onChildAdded is triggered?

Upvotes: 0

Views: 874

Answers (2)

Eddie
Eddie

Reputation: 139

I know this thread is quite old, but here's what worked for me

@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
       DatabaseReference parent = dataSnapshot.getRef().getParent();
       if( parent != null){
             String parentNode = parent.getKey();
       }
 }

So basically calling .getRef().getParent().getKey() on a Datasnapshot should do the work.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

Since you've only retrieved the child, the DataSnapshot does not contain the data for the parent item. But it is easily accessible at ref.

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

Upvotes: 2

Related Questions