简体   繁体   中英

How to rewrite code correctly with Firebase in cloud Firestore?

I wrote to connect to Firebase and now I want to transfer everything to cloud Firestore 1) the first method is written to get "Comment" from firebase

private void iniRvComment() {
        RvComment.setLayoutManager(new LinearLayoutManager(this));
        DatabaseReference commentRef = firebaseDatabase.getReference(COMMENT_KEY).child(postKey);
        commentRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                listComment = new ArrayList<>();
                for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                    Comment comment = snapshot.getValue(Comment.class);
                    listComment.add(comment);
                }
                commentAdapter = new CommentAdapter(getApplicationContext(), listComment);
                RvComment.setAdapter(commentAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

2) and how to rewrite this code to get "Comment" from the cloud firestore. What I wrote below is not correct

private void iniRvComment() {
        RwComment.setLayoutManager(new LinearLayoutManager(this));
        DocumentReference docRef = firestore.collection("Comment").document(postKey);
        docRef.collection("Comment").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                if (documentSnapshot != null && !documentSnapshot.getDocuments().isEmpty()) {
                    listComment = new ArrayList<>();
                    List<DocumentSnapshot> documents = documentSnapshot.getDocuments();
                    for (DocumentSnapshot value : documents) {

                        Comment comment = value.toObject(Comment.class);
                        listComment.add(comment);
                    }
                    commentAdapter = new CommentAdapter(getApplicationContext(), listComment);
                    RwComment.setAdapter(commentAdapter);
                }
            }
        });
    }

在此处输入图片说明

I recommend flattenning out your comments into a single, top-level Comments collection, rather than storing them under the post. This will allow you to perform many useful search operations such as searching all comments by user or post, or even creating a "recently active posts" feed.

To achieve, this you will need to change your database structure so that all comments are stored with the post they are attached to.

{
  content: "...",
  timestamp: 1234534568425,
  postId: "...",
  uid: "...",
  uimg: "...",
  uname: "..."
}

Once you have done that, you can now query comments by post using:

private final int PAGE_SIZE = 10;
private void iniRvComment() {
  RvComment.setLayoutManager(new LinearLayoutManager(this));

  firestore.collection("Comments") // this is a top level collection
    .whereEqualTo("postId", postKey) // select comments for given post
    .orderBy("timestamp", Query.Direction.DESCENDING) // order newest to oldest
    .limit(PAGE_SIZE) // fetch up to PAGE_SIZE recent comments
    .addSnapshotListener(new EventListener<QuerySnapshot>() {
      @Override
      public void onEvent(@Nullable QuerySnapshot results,
                          @Nullable FirebaseFirestoreException e) {
        if (e != null) {
          Log.w(TAG, "Listen failed.", e);
          return;
        }

        listComment = new ArrayList<>(PAGE_SIZE);
        for (QueryDocumentSnapshot commentDoc : results) {
          Comment commentObj = commentDoc.toObject(Comment.class);
          listComment.add(commentObj);
        }

        commentAdapter = new CommentAdapter(getApplicationContext(), listComment);
        RvComment.setAdapter(commentAdapter);
        Log.d(TAG, "Retrieved " + results.size() + " recent comments.");
      }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM