android-同时将评论发送到服务器,并将其提取到RecyclerView

时间:2020-04-20 18:59:42

标签: android android-recyclerview retrofit

我同时将评论发送到具有两个设备的服务器。稍后,我将它们添加到RecyclerView列表中。但有时未显示评论之一。代码:

private void makeComment(String comment) {

    Call<Model> call = restApiClass.commentPost(user_id, post_id, comment, date);
    call.enqueue(new Callback<Model>() {
        @Override
        public void onResponse(Call<Model> call, Response<Model> response) {

            if (response.body().isSuccess()) {
                //send a comment and later refresh the RecylerView to get new added comment.
                getComments();
            } 
    }

 private void getComments() {

    Call<List<CommentsModel>> call = restApiClass.getCommentsPost(post_id);
    call.enqueue(new Callback<List<CommentsModel>>() {
        @Override
        public void onResponse(Call<List<CommentsModel>> call, Response<List<CommentsModel>> response) {

            if (response.isSuccessful()) {

                    list = response.body();
                    if (commentsAdapter == null) {
                        commentsAdapter = new CommentsAdapter(list, getContext());
                        commentsRecyclerView.setAdapter(commentsAdapter );
                    }
                    //if there are already comments in Adapter don't create again
                    else {

                        commentsAdapter.addComment(list.get(list.size() - 1));
                        //go to last index of RecyclerView:
                        ((LinearLayoutManager) commentsPostRecyclerView.getLayoutManager()).
                                scrollToPositionWithOffset(list.size() - 1, 0);
                    }
             }

在CommentsAdapter中的addComment():

 public void addComment(CommentsModel comment) {
    this.list.add(comment);
    notifyItemInserted(this.list.size()-1); //item is added to last position.
}

0 个答案:

没有答案