-1

I have a data class which is populated by retrofit. The server (API) has no id field in it. So I created a val id and assigned it some value say 69. But once I receive the data, the value of id is not 69, but 0. Help please.

@Entity(tableName = "current_weather")
data class CurrentWeather(

    @SerializedName("last_updated_epoch")
    val lastUpdatedEpoch: Int,

// ... //

    @SerializedName("gust_kph")
    val gustKph: Float
) {
    @PrimaryKey(autoGenerate = false)
    var id: Int = 69
}

I even tried doing this:

data class CurrentWeather(

    @PrimaryKey(autoGenerate = false)
    val id: Int = 69,
// ... //
)

potatoxchip
  • 516
  • 1
  • 7
  • 20

2 Answers2

1
@Entity(tableName = "current_weather")
data class CurrentWeather(

    @PrimaryKey(autoGenerate = false)
    val id: Int = 69,

    @SerializedName("last_updated_epoch")
    val lastUpdatedEpoch: Int,

    // ... //

)

upd.

This is the object to ready to write to the database. For your case, you should write a mapper / converter from the Retrofit response object to the Data Entity data class.

tim4dev
  • 2,846
  • 2
  • 24
  • 30
  • No it is not working, I am populating the data class with retrofit. and there is no `id` field in the response, I am adding that myself. Is that the cause of the problem? – potatoxchip Jul 16 '19 at 02:35
1

Ok, this seems to be a problem with GSON, something with serialization and deserialization as it does not support kotlin properly. Read Gson Deserialization with Kotlin, Initializer block not called for more information.

potatoxchip
  • 516
  • 1
  • 7
  • 20