我有以下课程:
package com.mikhailovskii.trakttv.data.entity
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.mikhailovskii.trakttv.db.room.MovieIdConverter
@Entity
class Movie {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@SerializedName("ids")
@Expose
@TypeConverters(MovieIdConverter::class)
var movieId: MovieId? = null
@SerializedName("title")
@Expose
var name: String? = null
@SerializedName("year")
@Expose
var year: Int = 0
@SerializedName("tagline")
@Expose
var tagline: String? = null
@SerializedName("released")
@Expose
var released: String? = null
@SerializedName("runtime")
@Expose
var runtime: Int = 0
@SerializedName("country")
@Expose
var country: String? = null
@SerializedName("overview")
@Expose
var overview: String? = null
var iconUrl: String? = null
var watchers: Int = 0
//For movie list
@Ignore
constructor(iconUrl: String, name: String, year: Int, slugId: String, watchers: Int) {
this.iconUrl = iconUrl
this.name = name
this.year = year
this.movieId?.slug = slugId
this.watchers = watchers
}
//For movie detail
@Ignore
constructor(iconUrl: String, name: String, year: Int, tagline: String, released: String, runtime: Int, country: String, overview: String, slugId: String, watchers: Int) {
this.iconUrl = iconUrl
this.name = name
this.year = year
this.tagline = tagline
this.released = released
this.runtime = runtime
this.country = country
this.overview = overview
this.movieId?.slug = slugId
this.watchers = watchers
}
//For room
constructor(name: String, watchers: Int, iconUrl: String, slugId: String) {
this.iconUrl = iconUrl
this.movieId?.slug = slugId
this.watchers = watchers
this.name = name
}
}
此类用于多种目的,例如解析JSON对象,将数据添加到Room DB以及仅用于创建对象。而且我遇到了以下问题:
错误:实体和Pojos必须具有可用的公共构造函数。您可以使用空的构造函数,也可以使用参数与 字段(按名称和类型)。
public final class Movie {
^
我查看了先前关于同一问题的问题(尤其是this),据我了解,我的问题出在构造函数的这一行:
this.movieId?.slug = slugId
名称不匹配。但据我所知,没有机会匹配此名称,那么,如何解决此问题?
答案 0 :(得分:1)
您需要空的构造函数或所有参数构造函数。
因此,如果您添加constructor()
,问题就解决了
答案 1 :(得分:0)
因此,您无需向所有实体手动添加空的构造函数,可以使用a compiler plugin:
plugins {
id "org.jetbrains.kotlin.plugin.noarg" version "1.3.31"
}
noArg {
annotation("androidx.room.Entity")
}