Recyclerview Retrofit 2 - 如何在插入数据库后显示新项目

时间:2018-01-25 18:36:21

标签: android android-recyclerview retrofit2

我正在使用RecyclerView来显示评论列表,在底部(在RecyclerView之外)我有一个评论框,可以在列表中插入新评论。我能够将数据插入到数据库中,但我对如何通知适配器添加了新注释并将其显示在列表上一无所知。

我尝试做的只是在将新注释插入数据库后在列表顶部显示。

适配器

public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.CommentsHolder>{

private List<PostCommentsData> dataList;
private Context context;


public CommentsAdapter(Context applicationContext, List<PostCommentsData> commentsArrayList){
    this.dataList = commentsArrayList;
    this.context = applicationContext;
}

@Override
public CommentsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_post_comment, parent, false);
    return new CommentsHolder(view);

}

@Override
public void onBindViewHolder(CommentsHolder holder, int position) {
    Picasso.with(context).load(dataList.get(position).getComment_profile_image()).into(holder.ivProfileImage);
    holder.tvUserName.setText(dataList.get(position).getComment_username());
    holder.tvCommentDate.setText(dataList.get(position).getComment_datetime());
    holder.tvCommentBody.setText(dataList.get(position).getComment_body_text());
}

@Override
public int getItemCount() {
    return dataList == null ? 0 : dataList.size();
}

public static class CommentsHolder extends RecyclerView.ViewHolder{

    ImageView ivProfileImage;
    TextView tvUserName;
    TextView tvCommentDate;
    TextView tvCommentBody;

    public CommentsHolder(View itemView, final OnItemClickListener listener) {
        super(itemView);

        ivProfileImage = itemView.findViewById(R.id.comment_profile_image);
        tvUserName = itemView.findViewById(R.id.comment_username);
        tvCommentDate = itemView.findViewById(R.id.comment_date);
        tvCommentBody = itemView.findViewById(R.id.comment_text);
    }
  }
}

活动

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

    userSessionManager = new UserSessionManager(getApplicationContext());
    HashMap<String, String> user = userSessionManager.getUserDetails();
    userid = user.get(UserSessionManager.KEY_ID);

    Intent intent = getIntent();
    mPostID = intent.getStringExtra(EXTRA_POST_ID);
    newCommentBox = findViewById(R.id.CommentBox);
    newCommentButton = findViewById(R.id.CommentSendButton);

    initCommentsView();
    submitNewComment();

    swipeContainer = findViewById(R.id.CommentsSwipeContainer);
    swipeContainer.setColorSchemeResources(android.R.color.holo_orange_dark);
    swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            loadComments();
        }
    });
}

private void initCommentsView(){
    rvPostComments = findViewById(R.id.post_comments_recyclerview);
    rvPostComments.setLayoutManager(new LinearLayoutManager(this));
    postCommentsAdapter = new CommentsAdapter(this, null);
    rvPostComments.setAdapter(postCommentsAdapter);
    rvPostComments.smoothScrollToPosition(0);
    loadComments();
}

//This loads the comments list
private void loadComments(){

    String post_id = mPostID;
    postCommentsService = new PostCommentsService(this);
    postCommentsService.doGetPostComments(post_id, new Callback<PostCommentsList>() {
        @Override
        public void onResponse(Call<PostCommentsList> call, Response<PostCommentsList> response) {
            if(response.isSuccessful()){
                commentsListData = response.body().getPost_comments_list();
                postCommentsAdapter = new CommentsAdapter(getApplicationContext(), commentsListData);
                rvPostComments.setAdapter(postCommentsAdapter);
                swipeContainer.setRefreshing(false);
            }else{
                //do error stuff
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            //do failure stuff
        }
    });
}

//This is the submit function for new comments.

public void submitNewComment(){
    newCommentButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String newText = newCommentBox.getText().toString();
            String postID = mPostID;
            String userID = userid;

            postCommentsService = new PostCommentsService(PostCommentsActivity.this);
            postCommentsService.doAddNewComment(postID, userID, newText, new Callback() {
                @Override
                public void onResponse(Call call, Response response) {

                    PostCommentsData p = (PostCommentsData) response.body();
                    String msg = p.getMessage();

                    if(response.isSuccessful()){
                        if(!p.isError()){

                            //The message has been successfully added to the database.
                            //Now tell the adapter that there is a new comment and add it/show it on the list.
                            //How can this get done?

                        }else{
                            //do error stuff
                        }
                    }
                }

                @Override
                public void onFailure(Call call, Throwable t) {
                    //do failure stuff
                }
            });
        }
    });
}

如何从服务器获得响应后,使用新注释(将其添加到顶部)更新列表?

提前致谢,

1 个答案:

答案 0 :(得分:1)

在适配器中添加功能

public void addNewComment(PostCommentsData postCommentsData){
    this.dataList.add(0,postCommentsData);
    notifyItemInserted(0);
}

然后在数据库中添加注释时,在适配器对象上调用此函数。 <adapter>.addNewComment(comment)

PostCommentsData p = (PostCommentsData) response.body();
String msg = p.getMessage();
if (response.isSuccessful())
{
  if (!p.isError()) {
    postCommentsAdapter.addNewComment(p);

  } else {
    //do error stuff
  }
}