0

Disclaimer: I made this question and answer it myself because I need a "bigger board" to answer extended question of this post (as this whole explanation is never going to fit in comment

I'm having this data:

{
    "users" : {
        "randomUserId" : {
            "books" : {
                "booksId1" : true,
                "booksId2" : true
            }
        }
    },
    "books" : {
        "booksId1" : {
            "title" : "Awesome Book"
        },
        "booksId2" : {
            "title" : "Harry Potter"
        }
    }
}

I know I have to get users/randomUserId/books first then loop the dataSnapshot result to get all the book ids. Then I have to request detail data on each book id by using database reference that point to books/bookId?/. Something like this:

rootRef.child("users/" + user.getUid() + "books").addListenerForSingleValueEvent(new ValueEventListener() {
    ... onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot bookIdSnapshot : dataSnapshot) {
            rootRef.child("books/" + bookIdSnapshot.getValue(String.class))
                .addListenerForSingleValueEvent(...) {
                    // here i get the book detail data
                }
        }
    }
    ...
}

But with that code, each rootRef.child("books/"...) will be executed separately. So how can I know if the data have completely acquired?

Community
  • 1
  • 1
koceeng
  • 2,169
  • 3
  • 16
  • 37

1 Answers1

0

Actually we only need an int or double to indicate if full all related data is completely loaded, but we also need to use those data right? So it's better to use Map or HashMap instead.

int bookTotalCount = -1;
HashMap<String, Book> bookMap = new HashMap<String, Book>();

rootRef.child("users/" + user.getUid() + "books").addListenerForSingleValueEvent(new ValueEventListener() {
    ... onDataChange(DataSnapshot dataSnapshot) {
        bookTotalCount = dataSnapshot.getChildrenCount();
        for (DataSnapshot bookIdSnapshot : dataSnapshot) {
            rootRef.child("books/" + bookIdSnapshot.getValue(String.class))
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    ... onDataChange(DataSnapshot dataSnapshot) {
                        Book book = dataSnapshot.getValue(Book.class);
                        bookMap.put(dataSnapshot.getKey(), book);

                        if (bookMap.size() == bookTotalCount) {
                            // you can place code here
                            // in here, all the related data will be completely loaded
                        }
                    }
                });
        }
    }
    ...
}

Note: Book is a custom object created to contain data/value inside books/bookId?

koceeng
  • 2,169
  • 3
  • 16
  • 37