处理大量结构化数据的应用可极大地受益于在本地保留这些数据。最常见的使用场景是缓存相关的数据,这样一来,当设备无法访问网络时,用户仍然可以在离线状态下浏览该内容。
Room 持久性库在 SQLite 上提供了一个抽象层,以便在充分利用 SQLite 的强大功能的同时,能够流畅地访问数据库。具体来说,Room 具有以下优势:
- 提供针对 SQL 查询的编译时验证。
- 提供方便注解,可最大限度减少重复和容易出错的样板代码。
- 简化了数据库迁移路径。
出于这些方面的考虑,我们强烈建议您使用 Room,而不是直接使用 SQLite API。
@Entity(tableName = "Videoss") public class Video { @PrimaryKey private long id; @ColumnInfo private String videomainimg; @ColumnInfo private String videopath; @ColumnInfo private String caption; public Video(long id, String videomainimg, String videopath, String caption) { this.id = id; this.videomainimg = videomainimg; this.videopath = videopath; this.caption = caption; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getVideomainimg() { return videomainimg; } public void setVideomainimg(String videomainimg) { this.videomainimg = videomainimg; } public String getVideopath() { return videopath; } public void setVideopath(String videopath) { this.videopath = videopath; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } @Override public String toString() { return "Video{" + "id=" + id + ", videomainimg='" + videomainimg + '\'' + ", videopath='" + videopath + '\'' + ", caption='" + caption + '\'' + '}'; } }
数据库类为应用提供与该数据库关联的 DAO 的实例。反过来,应用可以使用 DAO 从数据库中检索数据,作为关联的数据实体对象的实例。此外,应用还可以使用定义的数据实体更新相应表中的行,或者创建新行供插入。图 1 说明了 Room 的不同组件之间的关系。
今天的重点是评论:
Api里的是基础:
@GET("/comment/getCommentByVideoId") Observable<CommentEntity> getCommentData(@Query("videoId") int videoId); @POST("/comment/comment") Observable<CommentEntity> postSendComment(@Body RequestBody body);
也需要实体类和适配器:
public class MyCommentAdapter extends BaseQuickAdapter<CommentEntity.DataBean, BaseViewHolder> { public MyCommentAdapter(int layoutResId) { super(layoutResId); } @Override protected void convert(@NonNull BaseViewHolder baseViewHolder, CommentEntity.DataBean dataBean) { ImageView imageView=baseViewHolder.getView(R.id.iv_head_comment); GlideUtil.loadciecleImage(getContext(),dataBean.getIcon(),imageView); baseViewHolder.setText(R.id.tv_user_comment,dataBean.getUsername()); baseViewHolder.setText(R.id.tv_message_comment,dataBean.getMsg()); } }
想要评论显示最重要的一步是:
mViewModel.commentLiveData.observe(this, new Observer<CommentEntity>() { @Override public void onChanged(CommentEntity commentEntity) { if (commentEntity.getCode()==200){ List<CommentEntity.DataBean> dataBeans=commentEntity.getData(); myCommentAdapter.getData().addAll(dataBeans); myCommentAdapter.notifyDataSetChanged(); tv_commetcount.setText(myCommentAdapter.getData().size()+"条评论"); } } }); mViewModel.sendcommentLiveData.observe(this, new Observer<CommentEntity>() { @Override public void onChanged(CommentEntity commentEntity) { if (commentEntity.getCode()==200){ Toast.makeText(getContext(), "发布评论成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(getContext(), "发布评论失败", Toast.LENGTH_SHORT).show(); } } });