0

I'm having an Entity class Damage

@Entity
class Damage(
        @PrimaryKey(autoGenerate = true)
        var damageId: Int,
        var position: String,
        var place: DamageItem? = null,
        var cause: DamageItem? = null
)

DamageItem is a regular POJO

data class DamageItem(
var itemId: String,
var itemDesc: String)

While trying to compile this code it is showing an error that

Cannot figure out how to save this field into database. You can consider adding a type converter for it.

I thought of first using @Embedded param for place and cause but found that is not the solution.

Is there anyway to solve this?

  • Possible duplicate of [Android room persistent library - TypeConverter error of error: Cannot figure out how to save field to database"](https://stackoverflow.com/questions/44582397/android-room-persistent-library-typeconverter-error-of-error-cannot-figure-ou) – denvercoder9 Nov 20 '19 at 10:56
  • Hi @sonnet Thanks for the quick response. The question you mentioned is regarding the converter needed for saving a List<> into database. My question is little bit different. I'm having same custom type for 2 of my columns. and somehow I'm getting this error. – Adhithya G Nair Nov 20 '19 at 11:01
  • you could write typeconverter and send back the string that will be saved in the table. also, give column names to your fields – denvercoder9 Nov 20 '19 at 11:05

2 Answers2

0

I found the answer is official documentation itself. Just by adding Embedded annotation with prefix to each of the custom data types

Official Doc

Changed my entity class to

@Entity class Damage(
    @PrimaryKey(autoGenerate = true)
    var damageId: Int,
    var position: String,
    @Embedded(prefix = "place_") var place: DamageItem? = null,
    @Embedded(prefix = "cause_") var cause: DamageItem? = null)
0

Well you didn't say, but I guess you are using Room. So there are a few ways of doing the thing you want.

 data class DamageItem (
  var itemId: String,
  var itemDesc: String
)
@Entity
class Damage (
        @PrimaryKey(autoGenerate = true)
        var damageId: Int,
        var position: String,
        @Embedded
        var place: DamageItem? = null,
        .... 
)

When multiple fields are closely related, but your data is not structured to create an object enclosing those multiple fields, @Embedded may be used to access the data as required, making the code more readable and maintainable.

This is used, if the variable needs to be accessed directly from the Object in your case "Damage".