Huy Tran
Huy Tran

Reputation: 69

The best way to get child's node data with random key in firebase?

This is one-to-many relationship: An author has many books

authors:
    randomAuthorId1:
        authorId: 
        authorName:
    randomAuthorId2:
        authorID: 
        authorName:
books:
    randomAuthorId1:
        randomBookId1:
            bookId:
            bookName:
        randomBookId2:
            bookId:
            bookName:
    randomAuthorId2:
        randomBookId3:
            bookId:
            bookName:

In my case, I don't have "randomAuthorId1", but I have "randomBookId2", this is my code to get the value of randomBookId2's node:

DatabaseReference bookRef = FirebaseDatabase.getInstance().getReference("books");
bookRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot data : dataSnapshot.getChildren()) {
            if (data.hasChild("randomBookId2")) {
                Book book = data.child("randomBookId2").getValue(Book.class);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

So, It has to loop through all children to get randomBookId2's node. Is there a better way? Thanks all

Upvotes: 4

Views: 673

Answers (2)

Dhaval Solanki
Dhaval Solanki

Reputation: 4705

You can do it by using Query but use query you need to update your Books DB like following the.
books:

randomAuthorId1:  
   randomBookId1:
        bookId:  
        randomBookId:randomBookId1
        bookName:
   randomBookId2:
        bookId:
        randomBookId:randomBookId2
        bookName:
randomAuthorId2:
    randomBookId3:
        bookId:
        randomBookId:randomBookId3
        bookName:

Now after that you can fire query like bellow

Query queryToGetData = databaseReference.child("books")
        .orderByChild("randomBookId").equalTo("randomBookId2");
queryToGetData.addChildEventListener(new ChildEventListener() {
    // TODO: 
    // ...
});

It will help you.

Upvotes: 3

Yossi
Yossi

Reputation: 347

You don't have a need to call hasChild in eventlistener if you know child name of which value you want to get.Instead of it just refer specific child and put it in try catch. So, if child not found then you can catch exception and perform actions as you want.

Sample Code:

try
{
    DatabaseReference bookRef = FirebaseDatabase.getInstance().getReference("books").child("randomBookId2");
    //add valueevent listener for this reference...
}catch(Exception e){
    //Child not found...perform action according this.
}

Upvotes: 1

Related Questions