简体   繁体   English

FirestoreRecyclerAdapter-如何知道何时检索数据?

[英]FirestoreRecyclerAdapter - how do I know when data has been retrieved?

I'm retrieving data using a FirestoreRecyclerAdapter , and, on completion, I need to check whether any items have been retrieved or not. 我正在使用FirestoreRecyclerAdapter检索数据,完成后,我需要检查是否已检索到任何项目。 I can't figure out how to do this. 我不知道该怎么做。

I'm calling it from a class called FragmentChartsList , shown below. 我从一个名为FragmentChartsList的类中调用它,如下所示。 This should set up the adapter initially, with "name" as the value for mOrder . 这应该首先设置适配器,并使用“ name”作为mOrder的值。 Later, the Activity which contains this Fragment can call setOrderField() with a different value of mOrder , which the user has selected from a Spinner. 稍后,包含此Fragment的Activity可以调用setOrderField() ,其值是mOrder ,用户已从Spinner中选择了该值。

Each time setOrderField() is called, a new adapter instance is created and attached to the recyclerView. 每次调用setOrderField() ,都会创建一个新的适配器实例并将其附加到recyclerView。 At this point I need to check whether the new version of the adapter contains any data, and either show a "no Charts found" message, or show the Charts which were retrieved (obviously if the list is just being sorted, then the number of items remains the same, but I'm going to be expanding this to allow the user to filter the Charts by different criteria, so the number of Charts returned will change). 在这一点上,我需要检查适配器的新版本是否包含任何数据,并显示“未找到图表”消息,或显示检索到的图表(显然,如果列表仅在排序中,则显示该数目)。项目保持不变,但我将对此进行扩展,以允许用户按不同条件过滤图表,因此返回的图表数将发生变化)。

Currently, setOrderField() calls refreshViewOnNewData() , which should find out how many Charts are being shown; 当前, setOrderField()调用refreshViewOnNewData() ,它应该找出正在显示的图表数量。 if it's 0, it should show the "no Charts found" message, and if it's >0 it should show the RecyclerView containing the Charts. 如果为0,则应显示“未找到图表”消息;如果大于0,则应显示包含图表的RecyclerView。

At the moment, I'm always getting a value of 0 when I try to count the Charts. 此刻,当我尝试计算图表时,总是得到0值。 I suspect it's because the adapter hasn't finished retrieving them from the database yet, but I can't find anything that allows me to add some kind of " onComplete " listener so that I know it's finished. 我怀疑这是因为适配器尚未完成从数据库中检索它们的操作,但是我找不到任何可以添加某种“ onComplete ”侦听器以使它知道完成的东西。

Can anyone suggest how I can achieve this? 谁能建议我如何实现这一目标?

public abstract class FragmentChartsList extends Fragment {

    private FirebaseFirestore mDatabaseRef;
    private ChartListAdapter mAdapter;
    private Query mChartsQuery;
    private RecyclerView mRecycler;
    private String mOrder = "name";

    private TextView mLoadingList, mEmptyList;

    public FragmentChartsList() {}

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(
                R.layout.fragment_charts_list, container, false);

        mRecycler = rootView.findViewById(R.id.charts_list);
        mRecycler.setHasFixedSize(true);

        mLoadingList = rootView.findViewById(R.id.loading_list);
        mEmptyList = rootView.findViewById(R.id.empty_list);

        // Set up Layout Manager, and set Recycler View to use it
        LinearLayoutManager mManager = new LinearLayoutManager(getActivity());
        mManager.setReverseLayout(true);
        mManager.setStackFromEnd(true);
        mRecycler.setLayoutManager(mManager);

        // Connect to the database
        mDatabaseRef = FirebaseFirestore.getInstance();

        setOrderField(mOrder); // Initialised to "name"

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        mAdapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        mAdapter.stopListening();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mAdapter.stopListening();
    }


    // HELPER FUNCTIONS

    public void setOrderField(String order) {

        mOrder = order;
        mChartsQuery = getQuery(mDatabaseRef, mOrder);

        // Update recycler options
        FirestoreRecyclerOptions<Chart> recyclerOptions = new FirestoreRecyclerOptions.Builder<Chart>()
                .setQuery(mChartsQuery, Chart.class)
                .build();

        mAdapter = new ChartListAdapter(recyclerOptions, getActivity());
        mAdapter.startListening();

        mRecycler.swapAdapter(mAdapter, true);

        refreshViewOnNewData();

    }

    private void refreshViewOnNewData() {

        // Hide "loading" text
        mLoadingList.setVisibility(View.GONE);

        // Check number of charts being shown
        //if (mAdapter != null && (mAdapter.getCount() > 0)) {
            // If > 0, show Charts
            mEmptyList.setVisibility(View.GONE);
            mRecycler.setVisibility(View.VISIBLE);

        } else {
            // If number of Charts = 0
            //    show "no charts"
            mEmptyList.setVisibility(View.VISIBLE);
            mRecycler.setVisibility(View.GONE);
        }

    }

}

The adapter class looks like this: 适配器类如下所示:

public class ChartListAdapter extends FirestoreRecyclerAdapter<Chart, ChartViewHolder> {

    private Activity mActivity;
    private int mCount;

    public ChartListAdapter(FirestoreRecyclerOptions<Chart> recyclerOptions, Activity activity) {
        super(recyclerOptions);

        mActivity = activity;

    }

    @Override
    protected void onBindViewHolder(@NonNull ChartViewHolder holder, int position, @NonNull Chart model) {

        final String chartKey = this.getSnapshots().getSnapshot(position).getId();

        model.setKey(chartKey);

        // Set click listener for the chart
        // On click, the user can view the chart
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, ActivityViewChart.class);
                intent.putExtra("ChartKey", chartKey);
                mActivity.startActivity(intent);
            }
        });

        // Implement long-click menu
        mActivity.registerForContextMenu(holder.itemView);

        // Bind Chart to ViewHolder
        holder.bindToChart(model);
    }

    @NonNull
    @Override
    public ChartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_chart, parent, false);

        return new ChartViewHolder(view);
    }

    @Override
    public void onDataChanged() {
        super.onDataChanged();

        mCount = getItemCount();

    }

    public int getCount() {
        return mCount;
    }

}

Figured this out... I needed to set a listener on the query instead. 想通了这一点...我需要在查询上设置一个侦听器。

So, instead of having the call to refreshViewOnNewData from setOrder above, I now have: 因此,我不再需要从上面的setOrder调用refreshViewOnNewDatasetOrder有了:

    mChartsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {


            if (queryDocumentSnapshots != null) {

                mLoadingList.setVisibility(View.GONE);

                if(queryDocumentSnapshots.size() > 0) {
                    mEmptyList.setVisibility(View.GONE);
                    mRecycler.setVisibility(View.VISIBLE);
                }else {
                    mEmptyList.setVisibility(View.VISIBLE);
                    mRecycler.setVisibility(View.GONE);
                }
            }

        }
    });

}

Also removed mCount from the adapter class, along with getCount and onDataChanged 还从适配器类中删除了mCount以及getCountonDataChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 FirestoreRecyclerAdapter 时如何获取 Firestore 文档 ID? - How do I get the Firestore document ID when using FirestoreRecyclerAdapter? 我如何知道是否已绘制视图 - How do I know if a view has been drawn 如何确保每次调用片段时都不会重新检索从服务器检索到的数据 - How to make sure that data that has been retrieved from a server is not re-retrieved every time a fragment is called 如果没有检索到数据,则 Firebase ChildEventListener - Firebase ChildEventListener if no data has been retrieved 我如何知道是否已调用 onSaveInstanceState() 以避免 IllegalStateException? - How do I know if onSaveInstanceState() has been called so that I can avoid the IllegalStateException? 我怎么知道一个Android应用程序是第一次加载的? - How do I know that an Android app has been loaded for the first time? HttpClient发布会话问题? 我如何知道会话是否已创建? - HttpClient Post session issue? How do I know if session has been created? 我如何知道该应用是否已从 Google Play 下载过一次 - How do I know if the app has been downloaded from Google Play once 过滤后如何知道列表视图中项目的ID? Android - how can i know the id of an item in the listview when it has been filtered? Android Compose - 如何知道何时渲染了子可组合 - Compose - How to know when a sub-composable has been rendered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM