Best way to get child node data with random key in firebase?

This is a one-to-many relationship: the 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 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 he has to iterate over all the children to get a randomBookId2 node. Is there a better way? Thank you all

+4
source share
2 answers

You can do this using Query, but using the query you need to update your Book Database, as shown below.
books:

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

Now after that you can run the query, for example, below.

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

This will help you.

+3

hasChild eventlistener, , . try catch. , , .

:

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.
}
+1

Source: https://habr.com/ru/post/1696087/


All Articles