apksherlock
apksherlock

Reputation: 8371

Issue with Room persistence after compilation

I have 2 data classes which are annotated with @Entity and proper configuration for Room to know what to compile.

For one of the classes, the build time fails and Android Studio yells at me saying that Room cannot find setters for field. With a little research , I changed my vals into vars and provided an empty constructor. Question is: Why the same problem doesn't happen with my other class which holds vals.

@Entity(tableName = "names_of_creator")
data class Name(
    @SerializedName("name")
    @ColumnInfo(name = "arabic_name")
    var arabicName: String,

    @SerializedName("transliteration")
    @ColumnInfo(name = "transliteration")
    var transliteration: String,

    @SerializedName("number")
    @PrimaryKey
    @ColumnInfo(name = "id")
    var number: Int,

    @SerializedName("en")
    @Ignore
    var englishNameMeaning: EnglishNameMeaning?,

    @ColumnInfo(name = "name_meaning")
    var meaning: String
){
    constructor(): this("", "", 0, null, "")
}

@Entity(
    tableName = "ayas",
    foreignKeys = [ForeignKey(
        entity = Surah::class,
        parentColumns = arrayOf("surah_number"),
        childColumns = arrayOf("surahs_number"),
        onDelete = CASCADE
    )]
)

data class Aya(
    @ColumnInfo(name = "aya_id")
    @PrimaryKey(autoGenerate = true)
    val id: Int,

    @SerializedName("audio")
    @ColumnInfo(name = "audio_url")
    val audioUrl: String,

    @SerializedName("text")
    @ColumnInfo(name = "ayat_text")
    val ayatText: String,

    @SerializedName("numberInSurah")
    @ColumnInfo(name = "ayat_number")
    val ayatNumber: Int,

    @SerializedName("juz")
    @ColumnInfo(name = "juz_number")
    val juz: Int,

    @ColumnInfo(name = "surahs_number", index = true)
    val surahNumber: Int
)

Upvotes: 0

Views: 59

Answers (1)

tynn
tynn

Reputation: 39843

Room will use a constructor to create the object. It'll use one it has all parameters available for. Since you @Ignore the englishNameMeaning, Room doesn't know which value to use. So just define a default value for this parameter.

@Entity(tableName = "names_of_creator")
data class Name(
    @SerializedName("name")
    @ColumnInfo(name = "arabic_name")
    val arabicName: String,

    @SerializedName("transliteration")
    @ColumnInfo(name = "transliteration")
    val transliteration: String,

    @SerializedName("number")
    @PrimaryKey
    @ColumnInfo(name = "id")
    val number: Int,

    @ColumnInfo(name = "name_meaning")
    val meaning: String

    @SerializedName("en")
    @Ignore
    val englishNameMeaning: EnglishNameMeaning? = null,
)

When Room doesn't want to support the Kotlin default argument, you might need to annotate the constructor with @JvmOverloads.

@Entity(tableName = "names_of_creator")
data class Name @JvmOverloads constructor(
    ...
)

Upvotes: 1

Related Questions