Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getItemCount() on Adapter is returning 0

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?

like image 338
TeeKay Avatar asked Jun 21 '16 06:06

TeeKay


Video Answer


1 Answers

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.

like image 164
Frank van Puffelen Avatar answered Oct 05 '22 07:10

Frank van Puffelen