0

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Rajesh
  • 77
  • 5
  • Try calling it inside populateView(), maybe data loading still in progress while you calling getCount(); – Geo Oct 19 '19 at 09:57
  • 2
    Firebase API's are asynchronous. In `FirebaseListAdapter` class, you're going to get a call for `populateView()` method for every child at that location. Have you tried to simply create inside the class a counter and increment it in `populateView()` method? – Alex Mamo Oct 19 '19 at 10:41
  • If you intend to use a `RecyclerView` instead of a `ListView`, then check my answer from this **[post](https://stackoverflow.com/questions/57587615/hide-recyclerview-when-there-is-no-item/57587887#57587887)**. – Alex Mamo Oct 20 '19 at 09:30

2 Answers2

1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

I had missed that Firebase API's are asynchronous. Used the onDataChanged() method given above by Frank. Worked like a charm.

Rajesh
  • 77
  • 5