![](/img/trans.png)
[英]Android Room - “Cannot figure out how to save this field into database.”
[英]How to save objects in room the database. Kotlin Android
我正在尝试将对象保存在房间数据库中。
我想保存在数据库中的个人资料 object class :
class Profile(
val exampleString : String = "Example String",
val exampleStringTwo : String = "Example String Two",
val subObjectsList : ArrayList<SubObjecst> = ArrayList()
)
配置文件 object 包括具有此结构的子对象的 Arraylist:
class SubObjects(
val exampleString : String = "Example 1",
val exampleStringTwo : String = "Example 2",
val exampleStringThree: String = "Example 3"
)
data class ProfileEntity(
@PrimaryKey(autoGenerate = true) val id: Long?,
@ColumnInfo(name = "profile") var profille: Profile
) : Parcelable
如何在房间数据库中保存配置文件 object? 我被困在这个 object 的类型转换器上。
TypeConverter
器类型转换器实际上用于转换简单类型,例如日期或枚举值,但它可以用于这种情况。 您需要有某种方法将您的SubObject
转换为String
,可能使用某种分隔符,您确信 object 字段中已经不存在。 所以像:
fun SubObject.toString() = "$exampleString@@$exampleString2@@$exampleString3"
然而,这并没有真正利用 SQL 的用途,即基于列的数据。
这可能是您想要的方法。 通过为您的Profile
和SubObject
模型设置一个单独的Entity
,您可以查询数据库以返回您的Profile
和SubObject
之间的关系,特别是在一对多的关系中。 在 Room 中,这是使用@Embedded
和@Relation
注释实现的。 我建议您在此处查看 Android Devleopers 文档,但对于您的示例,您需要以下内容:
class ResolvedProfile(
@Embedded
val profile: Profile,
@Relation(parentColumn = "profileId", entityColumn = "subObjectProfileId")
val subObjects: List<SubObject>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.