Reputation: 3084
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'
Upvotes: 0
Views: 1283
Reputation: 3084
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 object from it.
MyPost foundPost = postSnapshot.getValue(MyPost.class);
...
...
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Assign the query to FirebaseRecyclerAdapter here.
Upvotes: 1
Reputation: 755
Using the adapter, you can do it like this:
if (mAdapter.getItemCount() > 0) {
final Post = mAdapter.getItem(0);
}
You can find the source of the FirebaseRecyclerAdapter
here: https://github.com/firebase/FirebaseUI-Android/blob/master/database/src/main/java/com/firebase/ui/database/FirebaseRecyclerAdapter.java
Upvotes: 0