为了账号安全,请及时绑定邮箱和手机立即绑定

安卓 - 火库无限分页与听众

安卓 - 火库无限分页与听众

慕森王 2022-09-07 16:11:19
        我正在制作带有firebase firestore数据库的Android聊天应用程序,我需要与侦听器进行无限分页以进行数据更改(新按摩,删除按摩...我发现用kotlin和corse搜索的firebase文档写的博客文章,最终得到了这个代码:    // firstTime variable shows if function is called from pagination or initially    private void addMessagesEventListener(boolean firstTime) {            // get collection            CollectionReference messagesCollection =                         chatsCollection.document(chat.getId()).collection(Constants.FIREBASE_MESSAGES_PATH);    // create query    Query query = messagesCollection.orderBy("timestamp", Query.Direction.DESCENDING);    // if NOT first time add startAt    if (!firstTime) {        query.startAt(startTimestamp);    }    //limit to 20 messages    query.limit(20).get().addOnSuccessListener(queryDocumentSnapshots -> {        if (!firstTime) {            endTimestamp = startTimestamp;        }        startTimestamp = (long) queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1).get("timestamp");        Query innerQuery = messagesCollection.orderBy("timestamp").startAt(startTimestamp);        if(!firstTime) {            innerQuery.endBefore(endTimestamp);        }        ListenerRegistration listener = innerQuery                .addSnapshotListener((queryDocumentSnapshots1, e) -> {                    if (e != null) {                        Log.w(TAG, "listen:error", e);                        return;                    }
查看完整描述

2 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

试试这个


 @Override

 public void onStart() {

        super.onStart();


        loadFirstQuery();

 }



    public void loadFirstQuery() {



        if (firebaseAuth.getCurrentUser() != null) {


            contentListDashboard.clear();


            String currentUserId = firebaseAuth.getCurrentUser().getUid();              


            // what we do when recycler reach bottom

            recyclerProfileDashboard.addOnScrollListener(new RecyclerView.OnScrollListener() {

               @Override

               public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {

                   super.onScrolled(recyclerView, dx, dy);


                   // horizontal

                   //Boolean reachBottom = !recyclerView.canScrollHorizontally(-1);


                   // for vertical recycler

                   Boolean reachBottom = !recyclerView.canScrollVertically(-1);



                   if (reachBottom) {

                       loadMorePost(); // do load more post

                   }

               }

           });


            // RETRIEVING FIRST Query

            Query firstQuery = firebaseFirestore

                    .collection("ProfileDashboard")

                    .document(currentUserId)

                    .collection("ProfileInfo")

                    .orderBy("timestamp", Query.Direction.DESCENDING)

                    .limit(20);    


            firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {

                @Override

                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {


                    if (!documentSnapshots.isEmpty()) {

                        // please add if doc not empty

                        if (isFirstPageFirstLoad) {

                            lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1); // array 0, 1, 2

                        }


                        for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {


                            if (doc.getType() == DocumentChange.Type.ADDED) {


                                //String postId = doc.getDocument().getId();

                                contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);   



                                // if first page firest load true

                                if (isFirstPageFirstLoad) {

                                    contentListDashboard.add(contentProfileDashboard);

                                } else {

                                    contentListDashboard.add(0, contentProfileDashboard);

                                }



                                // fire the event

                                adapterProfileDashboard.notifyDataSetChanged();

                            }

                        }


                        isFirstPageFirstLoad = false;

                    }

                }

            });

        }

    }


   // Method to load more post

   public void loadMorePost() {


        if (firebaseAuth.getCurrentUser() != null) {


            String currentUserId = firebaseAuth.getCurrentUser().getUid();


            Query nextQuery = firebaseFirestore

                    .collection("ProfileDashboard")

                    .document(currentUserId)

                    .collection("ProfileInfo")

                    .orderBy("timestamp", Query.Direction.DESCENDING)

                    .startAfter(lastVisible)

                    .limit(20);


            nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {

                @Override

                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {


                    if (!documentSnapshots.isEmpty()) {


                        lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);

                        for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {


                            if (doc.getType() == DocumentChange.Type.ADDED) {


                                //String postId = doc.getDocument().getId();

                                // contentSeen = doc.getDocument().toObject(ContentProfile.class);

                                // contentList.add(contentSeen);


                                contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);

                                contentListDashboard.add(contentProfileDashboard);


                                //adapterSeen.notifyDataSetChanged();

                                adapterProfileDashboard.notifyDataSetChanged();


                            }

                        }

                    }

                }

            });

        }

   }

任何问题?


查看完整回答
反对 回复 2022-09-07
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

我发现了错误。工作代码是:


private void addMessagesEventListener(boolean firstTime) {

    CollectionReference messagesCollection = chatsCollection.document(chat.getId()).collection(Constants.FIREBASE_MESSAGES_PATH);

    Query query = messagesCollection.orderBy("timestamp", Query.Direction.DESCENDING);

    if (!firstTime) {

        query = query.startAt(startListen);

    }

    query.limit(20).get().addOnSuccessListener(queryDocumentSnapshots -> {

        if (!firstTime) {

            endListen = startListen;

        }

        startListen = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1);


        Query innerQuery = messagesCollection.orderBy("timestamp").startAt(startListen);

        if(!firstTime) {

            innerQuery = innerQuery.endBefore(endListen);

        }

        ListenerRegistration listener = innerQuery

                .addSnapshotListener((queryDocumentSnapshots1, e) -> {

                    if (e != null) {

                        Log.w("SASA", "listen:error", e);

                        return;

                    }


                    for (DocumentChange dc : queryDocumentSnapshots1.getDocumentChanges()) {

                        Message message = dc.getDocument().toObject(Message.class);

                        switch (dc.getType()) {

                            case ADDED:

                                // add new message to list

                                messageListAdapter.addMessage(message);

                                if (firstTime) {

                                    messagesList.smoothScrollToPosition(0);

                                }

                                break;

                            case REMOVED:

                                // remove message from list

                                messageListAdapter.removeMessage(message);

                                break;

                        }

                    }

                });

        listeners.add(listener);

    });

}

错误在于query = query.startAt(startListen)innerQuery = innerQuery.endBefore(endListen)


startListen & endListen 是 DocumentSnapshot type

我正在使用 sortedList 在我的适配器中

你应该添加


private void detachListeners() {

    for(ListenerRegistration registration : listeners) {

        registration.remove();

    }

}

在 onDestroy 中分离所有侦听器。


代码正在侦听添加新消息和删除旧消息。


查看完整回答
反对 回复 2022-09-07
  • 2 回答
  • 0 关注
  • 69 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号