Search code examples
javaandroidfirebasefirebase-realtime-databasefirebaseui

How to get count of elements present in FirebaseListAdapter?


I am using FirebaseListAdapter for the ListView and it is perfectly working fine. I have an additional requirement to display the count of elements present in the ListView. How do I do that?

I read through the documentation of FirebaseListAdapter and found that there is a method getCount() which is supposed to return the count of elements. But it is always returning zero. Below is the code I have. What am I missing?

    mAppointmentAdapter = new FirebaseListAdapter<Appointment>(options) {

    @Override
        public void populateView(View view, Appointment appointment, int position) {

            TextView nameTextView = view.findViewById(R.id.app_patient_name_view);
            TextView reasonTextView = 

         ...         
        }

    };
    appointmentListView.setAdapter(mAppointmentAdapter);

    // Display count of appointments
    int mAppointmentsCount;
    mAppointmentsCount = mAppointmentAdapter.getCount();
    mAppointmentsCountView.setText(String.valueOf(mAppointmentsCount));

Need the count of elements in the ListView or the adapter.


Solution

  • I think Alex has the correct idea here: most likely the items haven't been loaded from the database yet when you call mAppointmentAdapter.getCount(), so it correctly returns 0.

    That call should likely be inside populateView as Alex said, or in the onDataChanged method of your adapter. The onDataChanged gets called by FirebaseUI whenever it has updated the data, so that is the perfect place to also update your counter:

    @Override
    public void onDataChanged() {
      int mAppointmentsCount = mAppointmentAdapter.getCount();
      mAppointmentsCountView.setText(String.valueOf(mAppointmentsCount));
    }
    

    If this knowledge doesn't allow you to solve the problem, please edit your question to show when/where that call to mAppointmentAdapter.getCount() exists, as it makes it more likely we can help.