I have created an adapter which is working fine. Now, I need to get a count of the no of data items in the adapter. i am using the function getItemcount() ,but I am getting a 0 every time. ALso, I am using Firebase for handling my database.
final Firebase mRoot = new Firebase(FIREBASE_URL);
mPosts= mRoot.child("posts");
rvPosts.setHasFixedSize(true); //for performance improvement
rvPosts.setLayoutManager(new LinearLayoutManager(this)); //for vertical list
postAdapter = new FirebaseRecyclerAdapter<Hello, PostViewHolder>(Hello.class, R.layout.view_hello, PostViewHolder.class, mPosts.orderByChild("postedBy")) {
@Override
protected void populateViewHolder(final PostViewHolder postViewHolder, final Hello hello, int i) {
//do something
}
};
rvPosts.setAdapter(postAdapter);
int postForSelect = postAdapter.getItemCount();
What can be the problem?
The FirebaseRecyclerAdapter
asynchronously synchronizes data from the database to your app. When you print the number of items, none of the data has been synchronized yet.
To know whenever the data in an adapter changes, you can register an AdapterDataObserver
. For example in our Zero to App talk at I/O, we used this snippet to ensure the newest chat message would always be visible:
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
public void onItemRangeInserted(int positionStart, int itemCount) {
messagesList.smoothScrollToPosition(adapter.getItemCount());
}
});
I highly recommend you check out the full code for that minimal app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With