Litepal 数据库更新时报“XXX needs a default constructor.”

508 阅读1分钟

Litepal数据库调用更新时,需要迭代表内的非id字段,通过构建一个空的实例检查该字段是否等于默认值,来决定该字段是否更新。如果该表没有默认的无参构造方法则会抛 LitePalSupportException 异常。

当使用kotlin编写数据原型时,不能使用数据类data class,data class没有无参构造方法,需要将data class改为普通class。

 data class BloggerModel(
     var userId: String,
     var userName: String,
     var fullName: String,
     var tagLabel: String,
     var introInfo: String,
     var avatarUrl: String,
     var url: String,
     var visitTime:Long=0L, //最近一次的访问时间
     var count:Int=0,    //访问次数
     var id: Long = 0L
 ):LitePalSupport(),Serializable
 ​
 //修改为
 class BloggerModel() : LitePalSupport(), Serializable {
 ​
     constructor(
         userId: String,
         userName: String,
         fullName: String,
         tagLabel: String,
         introInfo: String,
         avatarUrl: String,
         url: String,
         visitTime: Long,
         count: Int,
         id: Long
     ) : this() {
         this.userId = userId
         this.userName = userName
         this.fullName = fullName
         this.tagLabel = tagLabel
         this.introInfo = introInfo
         this.avatarUrl = avatarUrl
         this.url = url
         this.visitTime = visitTime
         this.count = count
         this.id = id
     }
 ​
     lateinit var userId: String
     lateinit var userName: String
     lateinit var fullName: String
     lateinit var tagLabel: String
     lateinit var introInfo: String
     lateinit var avatarUrl: String
     lateinit var url: String
     var visitTime: Long = 0L //最近一次的访问时间
     var count: Int = 0    //访问次数
     var id: Long = 0L
 }
以下是断点跟踪过程

1、调用update(id)进行更新:

wecom-temp-0d86e667892cba4eb43977eed1601420.png wecom-temp-6fd8e34cf716f7405722dc89a8851d18-6293811.png

2、更新字段: wecom-temp-ea37cd19f2407d699b3626c23fd93dab-6293840.png

3、逐一迭代非id字段: wecom-temp-dd30dfce1251eaaf4fde17e1cecc93ec.png

4、当进行更新时,检查字段是否等于默认值(在这里抛出异常),不等于则更新该字段。当进行保存时直接更新字段,不需要检查: wecom-temp-3fb1e1dfaf00a5eecd27470926c62416-6294152.png

5、判断字段是否等于默认值 的具体代码,注释:分析传入的字段。检查此字段是否有默认值。 baseObj 需要一个默认构造函数,否则会抛出 LitePalSupportException。wecom-temp-1e24ed0995c09367b227561ea1376cb4.png

6、创建一个空实例: wecom-temp-79f0101f40f1f282ac3cc87e390859ab-6294251.png

7、newInstance()方法: wecom-temp-12301bf8646e1ce25f5df39cfc152447.png

综上,Litepal数据更新时会调用表的无参构造方法,编写表时需要注意保留无参构造方法。