henry000 henry000 - 4 months ago 155
Android Question

Access First Firebase Node Data in Firebase Query

I have a Firebase database query returning 100 child nodes. Then I put the nodes into a FirebaseRecyclerAdapter so the data is displayed on a recycler view. This is all working fine. Now I need to access the latest element and its Firebase key, but haven't been able to figure it out (should be easy, I must have missed something obvious). How do I get the latest element and its Firebase key in the returned query or adapter?

To get the 100 child nodes, I use:

Query publishedPostsQuery = mFirebaseDatabase.child("posts").limitToFirst(100);


I then populate a Firebase recycler adapter:

FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.post_items, PostViewHolder.class, postsQuery) { ... };


This adapter is then used in a recycler view.

How do I get to the first Post object and its Firebase key through either Query or FirebaseRecyclerAdapter?

My firebase database structure looks like:

-posts
-KLRDgtNht0iSB6RUGGz
- author: "author 1"
- title: "some post"
- detail: "blah blah"
-HGze53Sd4RRpFikdIKD
- author: "author 2"
- title: "great post"
- detail: "blah blah blah blah"


The version of Firebase I am using is:

compile 'com.firebaseui:firebase-ui-database:0.4.0'
compile 'com.google.firebase:firebase-database:9.0.2'

Answer

I figured it out. To find a particular node, in my case the latest post (presented as a Post object based on the given data structure shown on my question), I had to use addListenerForSingleValueEvent to get the Firebase DataSnapshot, then from there I can loop through the children nodes to find what I want.

    Query publishedPostsQuery = mFirebaseDatabase.child("posts")
            .limitToFirst(100);

    publishedPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getChildrenCount() != 0) {
                Iterable<DataSnapshot> i = dataSnapshot.getChildren();
                for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                  // Find the particular node (e.g. last node, first node... etc) here and create a Post object.
                  MyPost foundPost = postSnapshot.getValue(MyPost.class);
                  ...
                  ...
                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

    // Assign the query to FirebaseRecyclerAdapter here.
Comments