从OnSuccessListener(Firestore)

时间:2018-03-13 08:09:45

标签: android firebase firebase-realtime-database android-recyclerview google-cloud-firestore

我有一个recyclelerView,可以直接从onCreate调用时加载。但是,当将其插入到Firestore Collection的onSuccessListener中时,它不会加载。以下是所述代码的示例:

private void populateRecycler(String RootCollection, String UserID) {
    mQuery = mFirestore
            .collection(RootCollection)
            .whereEqualTo("UID", UserID)
            .orderBy("DateAdded", Query.Direction.DESCENDING);
    mAdapter = new OrdersAdapter(mQuery, this) {
        @Override
        protected void onDataChanged() {
            if (getItemCount() == 0) {
                mOrdersRecycler.setVisibility(View.GONE);
                mEmptyView.setVisibility(View.VISIBLE);
            } else {
                mOrdersRecycler.setVisibility(View.VISIBLE);
                mEmptyView.setVisibility(View.GONE);
            }
        }
        protected void onError (FirebaseFirestoreSettings e) {
            // Show a snackbar on errors
            Snackbar.make(findViewById(android.R.id.content),
                    "Error: check logs for info.", Snackbar.LENGTH_LONG).show();
        }
    };

    // Populate and enable RecyclerView
    mOrdersRecycler.setLayoutManager(new LinearLayoutManager(this));
    mOrdersRecycler.setAdapter(mAdapter);
}

但是当我从另一个包含此代码的方法调用populateRecycler();时:

mFirestore.collection("UIDOrg")
            .document(UserID)
            .get()
            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                @Override
                public void onSuccess(DocumentSnapshot documentSnapshot) {
                    UIDOrg uidOrg = documentSnapshot.toObject(UIDOrg.class);
                    mOrgTextView.setText(uidOrg.getOrg());
                    RootCollection = uidOrg.getRootCollection();
                    populateRecycler(RootCollection, UserID);

                }

......它不起作用。有人可以解释一下原因吗?

1 个答案:

答案 0 :(得分:1)

  mQuery = mFirestore
        .collection(RootCollection)
        .whereEqualTo("UID", UserID)
        .orderBy("DateAdded", Query.Direction.DESCENDING);
populateRecycler方法中的

是异步操作。这意味着将来可以获得结果。因此,您需要在填充数据之前等待结果。

阅读此概念chaining of the tasks。完成第二项任务后,再填充您的回收者视图。