Android Room library error: Cannot find setter for

2019-07-08 04:29发布

问题:

I am using room library and I have below mentioned entity:

@Parcelize
@Entity(tableName = "tb_option")
data class OptionsTable(
        var question_id: Int? = null,
        var option_id: Int? = null,
        var option: String? = null,
        var is_selected: Int? = null,


        @PrimaryKey(autoGenerate = true)
        var sr_no: Int = 0) : Parcelable

as you can see I have all the field declared as var but it is still showing error as:

error: Cannot find setter for field.
e: 

e:     private java.lang.Integer is_selected;
e:      



                     ^

please suggest some fix for this.

Thanks

回答1:

Most of the time issue is occurring because of the following:

Problem 1:

Final field: Fields are marked with val, they are effectively final and don't have setter fields.

Solution: Replace the fields val with var. You might also need to initialize the fields.

Problem 2:

is keyword: We cannot use sqllite reserved keywords line for fields naming source e.g.

The following will cause error

 @ColumnInfo(name = "IS_ACTIVE") var isActive

Solution: The solution is:

@ColumnInfo(name = "IS_ACTIVE") var active


回答2:

I removed the initialization of sr_no from

@PrimaryKey(autoGenerate = true)
        var sr_no: Int = 0

and the final code is:

@PrimaryKey(autoGenerate = true)
        var sr_no: Int

worked for me because it was an auto-generated field.



回答3:

There is an issue in room orm library with kotlin java code generation.

My optional field isFavorite and compile time same error then I change my field name to favorite then compiled.

before var isFavorite: Int? = 0, working fine: var favorite: Int? = 0, Thanks