如何获取 FirebaseListAdapter 中存在的元素数量?

How to get count of elements present in FirebaseListAdapter?

我正在为 ListView 使用 FirebaseListAdapter,它运行良好。我还有一个额外的要求,即显示 ListView 中存在的元素数。我该怎么做?

我通读了 FirebaseListAdapter 的文档,发现有一个方法 getCount() 应该 return 计算元素的数量。但它总是 returning 为零。下面是我的代码。我错过了什么?

    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));

需要 ListView 或适配器中的元素计数。

我认为 Alex 在这里的想法是正确的:当您调用 mAppointmentAdapter.getCount() 时,很可能还没有从数据库加载项目,所以它是正确的 returns 0

正如 Alex 所说,该调用可能在 populateView 内,或者在您的适配器的 onDataChanged method 内。 onDataChanged 每当更新数据时都会被 FirebaseUI 调用,因此这是更新计数器的最佳位置:

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

如果这些知识不允许您解决问题,请编辑您的问题以显示 when/where 调用mAppointmentAdapter.getCount() 存在,因为它使我们更有可能提供帮助。

我错过了 Firebase API 是异步的。使用了 Frank 上面给出的 onDataChanged() 方法。工作得很好。