RecyclerView不显示数据

时间:2019-06-27 16:34:55

标签: java android firebase android-recyclerview

Screenshot of my Database我尝试使用Firebase为Android创建博客应用程序,并且需要创建一个RecyclerView以显示所有帖子。

我的代码被编译,我添加了一些数据,但是当我连接手机时,数据没有显示,我真的不明白为什么。

这是我的片段:


    private RecyclerView forum_list_view;
    private List<Post> forum_list;

    private FirebaseFirestore firebaseFirestore;
    private FirebaseAuth firebaseAuth;
    private ForumRecyclerAdapter forumRecyclerAdapter;

    private DocumentSnapshot lastVisible;
    private Boolean isFirstPageFirstLoad = true;

    public ForumFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_forum, container, false);

        forum_list = new ArrayList<>();
        forum_list_view = view.findViewById(R.id.forum_list_view);

        firebaseAuth = FirebaseAuth.getInstance();

        forumRecyclerAdapter = new ForumRecyclerAdapter(forum_list);
        forum_list_view.setLayoutManager(new LinearLayoutManager(container.getContext()));
        forum_list_view.setAdapter(forumRecyclerAdapter);
        forum_list_view.setHasFixedSize(true);

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

            firebaseFirestore = FirebaseFirestore.getInstance();

            forum_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    Boolean reachedBottom = !recyclerView.canScrollVertically(1);

                    if(reachedBottom){

                        loadMorePost();

                    }

                }
            });

            Query firstQuery = firebaseFirestore.collection("Post").orderBy("date", Query.Direction.DESCENDING).limit(3);
            ListenerRegistration listener = firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                    if (!documentSnapshots.isEmpty()) {

                        if (isFirstPageFirstLoad) {

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

                        }

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

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

                                String postId = doc.getDocument().getId();
                                Post post = doc.getDocument().toObject(Post.class).withId(postId);

                                if (isFirstPageFirstLoad) {

                                    forum_list.add(post);

                                } else {

                                    forum_list.add(0, post);

                                }


                                forumRecyclerAdapter.notifyDataSetChanged();

                            }
                        }

                        isFirstPageFirstLoad = false;

                    }

                }

            });
            listener.remove();
        }
        // Inflate the layout for this fragment
        return view;
    }

    private void loadMorePost(){

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

            Query nextQuery = firebaseFirestore.collection("Post")
                    .orderBy("date", Query.Direction.DESCENDING)
                    .startAfter(lastVisible)
                    .limit(3);

            ListenerRegistration listener = 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();
                                Post post = doc.getDocument().toObject(Post.class).withId(postId);
                                forum_list.add(post);

                                forumRecyclerAdapter.notifyDataSetChanged();
                            }

                        }
                    }

                }
            });

            listener.remove();
        }

    }

}

我的适配器:


    public List<Post> blog_list;
    public Context context;

    private FirebaseFirestore firebaseFirestore;
    private FirebaseAuth firebaseAuth;

    public ForumRecyclerAdapter(List<Post> blog_list){

        this.blog_list = blog_list;

    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.forum_list_item, parent, false);
        context = parent.getContext();
        firebaseFirestore = FirebaseFirestore.getInstance();
        firebaseAuth = FirebaseAuth.getInstance();
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.setIsRecyclable(false);

        final String blogPostId = blog_list.get(position).PostId;
        final String currentUserId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getUid();

        String body_data = blog_list.get(position).getBody();
        String category = blog_list.get(position).getCategory();
        String title = blog_list.get(position).getTitle();

        holder.setBodyText(body_data);
        holder.setCategory(category);
        holder.setTitle(title);

        String user_id = blog_list.get(position).getAuthor();

        firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                if(task.isSuccessful()){

                    String userName = Objects.requireNonNull(task.getResult()).getString("name");

                    holder.setUserData(userName);


                } else {

                    //Firebase Exception
                    Toast.makeText(context, "Exception", Toast.LENGTH_SHORT).show();

                }

            }
        });

        try {
            long millisecond = blog_list.get(position).getDate().getTime();
            String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
            holder.setTime(dateString);
        } catch (Exception e) {

            Toast.makeText(context, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();

        }
        //Get Likes Count
        firebaseFirestore.collection("Post/" + blogPostId + "/likes").addSnapshotListener( new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                if(!documentSnapshots.isEmpty()){

                    int count = documentSnapshots.size();

                    holder.updateLikesCount(count);

                } else {

                    holder.updateLikesCount(0);

                }

            }
        });

        //Likes Feature
        holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                firebaseFirestore.collection("Post/" + blogPostId + "/likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                        if(!task.getResult().exists()){

                            Map<String, Object> likesMap = new HashMap<>();
                            likesMap.put("timestamp", FieldValue.serverTimestamp());

                            firebaseFirestore.collection("Post/" + blogPostId + "/likes").document(currentUserId).set(likesMap);

                        } else {

                            firebaseFirestore.collection("Post/" + blogPostId + "/likes").document(currentUserId).delete();

                        }

                    }
                });
            }
        });

        holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent commentIntent = new Intent(context, AnswerActivity.class);
                commentIntent.putExtra("blog_post_id", blogPostId);
                context.startActivity(commentIntent);

            }
        });
    }

    @Override
    public int getItemCount() {
        return blog_list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private View mView;

        private TextView bodyView;
        private ImageView blogImageView;
        private TextView blogDate;

        private TextView blogUserName;
        private CircleImageView blogUserImage;

        private ImageView blogLikeBtn;
        private TextView blogLikeCount;

        private ImageView blogCommentBtn;
        private TextView blogCategory;
        private TextView blogTitle;


        public ViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

            blogLikeBtn = mView.findViewById(R.id.post_like_btn);
            blogCommentBtn = mView.findViewById(R.id.post_comment_icon);

        }

        public void setBodyText(String bodyText){

            bodyView = mView.findViewById(R.id.post_body);
            bodyView.setText(bodyText);

        }

        public void setTime(String date) {

            blogDate = mView.findViewById(R.id.post_date);
            blogDate.setText(date);

        }

        /*public void setUserData(String name, String image){

            blogUserImage = mView.findViewById(R.id.post_user_image);
            blogUserName = mView.findViewById(R.id.post_user_name);

            blogUserName.setText(name);

        }*/

        public void updateLikesCount(int count){

            blogLikeCount = mView.findViewById(R.id.post_like_count);
            blogLikeCount.setText(count + " Likes");

        }

        public void setCategory(String category){
            blogCategory = mView.findViewById(R.id.post_category);
            blogCategory.setText(category);
        }

        public void setTitle(String title){
            blogTitle = mView.findViewById(R.id.post_title);
            blogCategory.setText(title);
        }

        public void setUserData(String userName) {
            blogUserName = mView.findViewById(R.id.post_author);

            blogUserName.setText(userName);
        }
    }
}

我的帖子模型:

    public String author;
    public String body;
    public String title;
    public Date date;
    public String category;

    public Post(String author, String body, String title, Date date, String category) {
        this.author = author;
        this.body = body;
        this.title = title;
        this.date = date;
        this.category = category;
    }

    public String getAuthor() {
        return author;
    }


    public String getTitle() {
        return title;
    }

    public String getBody() {
        return body;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }


}

我真的没有任何错误,我认为一切都可以正常运行,但是那不是

0 个答案:

没有答案