简体   繁体   English

为什么 firebase 无法在回收站视图中查询集合中的数据?

[英]Why firebase is not able to query data from collection in recycler view?

I am able to get data in firebase collection but it does not query that data in recycler view.我能够在 firebase 集合中获取数据,但它不会在回收器视图中查询该数据。 Recyclerview does not showing anything Recyclerview 不显示任何内容在此处输入图像描述

This is the comment_list class.这是 comment_list class。

public class comment_list {
    public comment_list(String comments) {
        this.comments = comments;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    String comments;
}

This is comment_adapter class这是 comment_adapter class

public class comment_adapter extends FirestoreRecyclerAdapter<comment_list, comment_adapter.comment_holder> {
  
    public comment_adapter(@NonNull FirestoreRecyclerOptions<comment_list> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull comment_holder holder, int position, @NonNull comment_list model) {
        holder.commment_on_post.setText(model.getComments());
    }

    @NonNull
    @Override
    public comment_holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_recycler_dsign, parent, false);
        return new comment_holder(v);
    }

    public class comment_holder extends RecyclerView.ViewHolder{
      TextView commment_on_post;
        public comment_holder(@NonNull View itemView) {
            super(itemView);
            commment_on_post = itemView.findViewById(R.id.commenttextview);
        }
    }

This is Comments class. In this I am able to get data in firebase collection but it is not query that data in recycler view.这是评论 class。在此我能够获取 firebase 集合中的数据,但它不是在回收器视图中查询该数据。

public class Comments extends AppCompatActivity {
 ImageView profileimage;
 EditText addcommenttext;
 TextView postcommenttext;
    FirebaseFirestore db;
  
    RecyclerView comment_recycler_view;

   comment_adapter adaptercomment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comments);

        profileimage = findViewById(R.id.Addcommentprofileimage);
        addcommenttext = findViewById(R.id.addcommenttext);
        postcommenttext = findViewById(R.id.postcomment);
    
comment_recycler_view = findViewById(R.id.commentsrecycler);




        postcommenttext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addcommenttext.equals("")) {
                    Toast.makeText(Comments.this, "Comment can't be empty", Toast.LENGTH_SHORT).show();
                } else {
                    String commentText = addcommenttext.getText().toString();

                    CollectionReference commentref = FirebaseFirestore.getInstance() .collection("CommentDetails");
                    commentref.add(new comment_list(commentText));

         

                    
                    FirebaseFirestore fbfs = FirebaseFirestore.getInstance();
                    CollectionReference commentrefs = fbfs.collection("CommentDetails");
                    Query query = commentrefs;

                    FirestoreRecyclerOptions<comment_list> options = new FirestoreRecyclerOptions.Builder<comment_list>()
                            .setQuery(query, comment_list.class)
                            .build();
                    adaptercomment = new comment_adapter(options);

                    comment_recycler_view.setHasFixedSize(true);
                    comment_recycler_view.setLayoutManager(new LinearLayoutManager(getApplication()));
                    comment_recycler_view.setAdapter(adaptercomment);
                    finish();
                    Toast.makeText(Comments.this, "Commented", Toast.LENGTH_SHORT).show();

                }
            }


    });

}

First of all, let's reconfigure your Comments activity class. It would be recommended to initialise the recycle adapter in your onCreate method and not in the overridden onClick method.首先,让我们重新配置您的Comments活动 class。建议在您的onCreate方法中而不是在覆盖的onClick方法中初始化回收适配器。 With the current set up, a new comment_adapter is initialised every time the onClick listener is triggered.使用当前设置,每次触发 onClick 侦听器时都会初始化一个新的comment_adapter It's best that we set-up only one.我们最好只设置一个。 Here's how things look after the changes (I've added comments for clarity):以下是更改后的情况(为清楚起见,我添加了注释):

NOTE: I have renamed classes, variables and methods to use java and android conventions for clarity.注意:为清楚起见,我已将类、变量和方法重命名为使用 java 和 android 约定。 Learning these will help you a lot in being able to read others code and save you a lot of headaches with your own code.学习这些将极大地帮助您阅读他人的代码,并为您编写自己的代码省去很多麻烦。

public class CommentsActivity extends AppCompatActivity {

    FirebaseFirestore db;
    CommentAdapter commentAdapter;

    ImageView profileImageView;
    EditText commentEditText;
    RecyclerView commentRecyclerView;
    Button addCommentButton; // Replaces the text view you are using

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        profileImageView = findViewById(R.id.add_comment_profile_image);
        commentEditText = findViewById(R.id.comment_edit_text);
        addCommentButton = findViewById(R.id.add_comment_button);
        commentRecyclerView = findViewById(R.id.comments_recycle_view);

        // Enables firestore debugging which will help a lot when trying to troubleshoot
        FirebaseFirestore.setLoggingEnabled(true);

        // We are now setting up our query directly within the OnCreate method.
        db = FirebaseFirestore.getInstance();
        Query query = db.collection("CommentDetails").orderBy("timestamp").limit(50);

        FirestoreRecyclerOptions<Comment> options = new FirestoreRecyclerOptions.Builder<Comment>()
                .setQuery(query, Comment.class)
                .build();

        // Setting up the recycle adapter in onCreate
        commentAdapter = new CommentAdapter(options);
        commentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        commentRecyclerView.setAdapter(commentAdapter);

        // Set up your onClickListener just as before.
        addCommentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Note that the previous null check is unsuccessful. Previously, the object instance
                // was being checked, and not the contents of the edit text. This resolves that issue. (:
                if (commentEditText.toString().isEmpty()) {
                    Toast.makeText(CommentsActivity.this, "Comment can't be empty", Toast.LENGTH_SHORT).show();
                } else {
                    String commentText = commentEditText.getText().toString();
                    CollectionReference commentColRef = FirebaseFirestore.getInstance().collection("CommentDetails");
                    commentColRef.add(new Comment(commentText));
                    Toast.makeText(CommentsActivity.this, "Commented", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        commentAdapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        commentAdapter.stopListening();
    }
}

You will notice the addition of two new methods: onStart and onStop .您会注意到添加了两个新方法: onStartonStop Within these methods we start and stop the query listeners attached to the FirestoreRecyclerAdapter .在这些方法中,我们启动和停止附加到FirestoreRecyclerAdapter的查询侦听器。 It will be really helpful to refer to the FirebaseUI for Cloud Firestore read-me .参考Cloud Firestore 自述文件的 FirebaseUI会很有帮助。

It is important to note in the code above I also renamed your data model from comment_list to Comment .请务必注意,在上面的代码中,我还将您的数据 model 从comment_list重命名为Comment The reason for this, is that an instance of this class only stores the state of one comment.这样做的原因是,这个 class 的实例只存储了一条评论的 state。 It does not store a list of comments.它不存储评论列表。 I think it might cause confusion when you are trying to debug your code.我认为这可能会在您尝试调试代码时引起混淆。 In the case of using FirebaseUI, the actual list of comments (the comments list ) which is bound to your recycle view is built for you by the FirebaseUI code, in the form of an array of Comment class instances.在使用 FirebaseUI 的情况下,绑定到回收视图的实际评论列表(评论列表)由 FirebaseUI 代码以Comment class 实例数组的形式为您构建。

In order to understand clearly how this is done, it might be useful to spend a couple of hours implementing a simple recycle view and adapter that is not connected to Firestore.为了清楚地了解这是如何完成的,花几个小时实现一个未连接到 Firestore 的简单回收视图和适配器可能会很有用。 That way a greater understanding as to how FirebaseUI is doing things can be developed.这样可以更好地理解 FirebaseUI 是如何做事的。 There are docs on that here . 这里有相关文档。

Finally - here is a replacement to the comment_list class:最后 - 这是 comment_list class 的替换:

public class Comment {

    String comment;
    @ServerTimestamp Date timestamp;

    // A zero argument constructor is required by firestore.
    public Comment() {
    }

    public Comment(String comment) {
        this.comment = comment;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

The only difference here is there is a zero-args (no argument) constructor, which is required by firestore.这里唯一的区别是有一个零参数(无参数)构造函数,这是 firestore 所必需的。

A word to the wise - I haven't seen your view model item layout ( comment_recycler_dsign ), but just check that the root layout does not have a height of "match_parent".明智的一句话 - 我没有看到你的视图 model 项目布局( comment_recycler_dsign ),但只是检查根布局没有“match_parent”的高度。 This is a common mistake.这是一个常见的错误。 It is a good idea to check this first if you see only one recycle item being rendered.如果您只看到一个回收项目被渲染,最好先检查一下。

Place a listener fire base will automatically call once the upload is complete放置一个侦听器火力基地将在上传完成后自动调用

 firestore.collection("").add(Any()).addOnCompleteListener { 
                    // do all your work here
 }

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

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