android 收藏功能

首先创建数据库存放数据

public class LikePeise extends LitePalSupport implements Parcelable {
    private String title ;
    private int image;
    private boolean collect;

    public LikePeise(String title, int image, boolean collect) {
        this.title = title;
        this.image = image;
        this.collect = collect;
    }

    public LikePeise() {
    }

    public String getTitle() {
        return title;
    }

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

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public boolean isCollect() {
        return collect;
    }

    public void setCollect(boolean collect) {
        this.collect = collect;
    }

    protected LikePeise(Parcel in) {

        title = in.readString();
        collect = in.readByte() != 0;
        image = in.readInt();

    }

    public static final Creator<LikePeise> CREATOR = new Creator<LikePeise>() {
        @Override
        public LikePeise createFromParcel(Parcel in) {
            return new LikePeise(in);
        }

        @Override
        public LikePeise[] newArray(int size) {
            return new LikePeise[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

        dest.writeByte((byte) (collect ? 1 : 0));
        dest.writeByte((byte) (collect ? 1 : 0));
        dest.writeString(title);
        dest.writeInt(image);
    }

    public boolean saveOrUpdate() {
        if (TextUtils.isEmpty(title)) {
            return false;
        }
        return super.saveOrUpdate("title=?", title);
    }
}

创建查询方法

  public List<LikePeise> findCollects(String title) {
        return LitePal.where("title = ? ", title).find(LikePeise.class);
//        return LitePal.where("collect = ? ", "1").find(LikePeise.class);
    }

将查询到的数据存放集合并赋值

         //将收藏的数据存入到集合中
        List<LikePeise> collects = findCollects(peise.getTitle());
        //将数据赋值
        if (collects.isEmpty()) {
            likePeise = new LikePeise(peise.getTitle(), peise.getImage(), false);
        } else {
            likePeise = collects.get(0);
        }

然后

   //通过判断是否收藏来设置收藏按钮状态
        binding.shoucang.setChecked(likePeise.isCollect());
  binding.shoucang.setOnCheckedChangeListener((buttonView, isChecked) -> {
            Log.d(TAG, "shoucang: " + isChecked);
            if (null != likePeise) {
                likePeise.setCollect(isChecked);
                likePeise.saveOrUpdate();
            }
        });

最后将数据更新

  • 2
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值