FirestoreRecyclerAdapter取决于注册的侦听器

时间:2019-05-15 18:08:54

标签: android android-recyclerview google-cloud-firestore

我正在使用FirestoreRecyclerAdapter来显示RecyclerView中的项目。当我在活动的adapter.startListening();中调用onStart()时,适配器在运行时为空。我决定为与适配器相同的查询注册一个侦听器,并将Objects的列表传递给适配器的onBindViewHolder,它可以正常工作。这是我的适配器

private void loadList(Query query) {

    recycler.setHasFixedSize(true);
    LinearLayoutManager manager = new LinearLayoutManager(this);
    recycler.setLayoutManager(manager);

    FirestoreRecyclerOptions<Post response = new FirestoreRecyclerOptions.Builder<Post()
            .setQuery(query, Post.class)
            .build();

    adapter = new FirestoreRecyclerAdapter<Post, PostViewHolder(response) {

        @Override
        protected void onBindViewHolder(PostViewHolder holder, int position, Post model) {

            //holder.setData(postList.get(position));

            holder.setData(model);

        }

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

            return new PostViewHolder(view);
        }

        @Override
        public void onError(FirebaseFirestoreException e) {
            Log.e("error", e.getMessage());
        }
    };

    adapter.notifyDataSetChanged();
    recycler.setAdapter(adapter);
}

没有此注册的侦听器,我的适配器始终为空:

firestoreListener = query
    .addSnapshotListener(new EventListener<QuerySnapshot() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            if (e != null) {
                //Log.e(TAG, "Listen failed!", e);
                return;
            }

            postList = new ArrayList<();

            for (DocumentSnapshot doc : documentSnapshots) {
                Post post = doc.toObject(Post.class);
                postList.add(post);
            }

            adapter.notifyDataSetChanged();
            recycler.setAdapter(adapter);
        }
    });

这通常应该怎么做?我认为传递到FirestoreRecyclerOptions中的适配器的查询已足够,当我调用adapter.startListening();

时,适配器将开始监听

0 个答案:

没有答案