当前位置: 首页 > 知识库问答 >
问题:

嵌套数组错误:无法找出如何将此字段保存到数据库中。您可以考虑为其添加类型转换器

丁景山
2023-03-14

这是第一次使用Room数据库,我想将数据保存到嵌套类中

植物种类:

@Entity
data class Plant(

    @PrimaryKey  var id:Long,
    @ColumnInfo (name="plant_name") var name: String,
    @ColumnInfo(name ="plant_type") var type: Plant_Category,
    @ColumnInfo(name= "plant_image") var image: Int,

    ) {

}

这是植物类别类:

@Entity
data class Plant_Category(

    @PrimaryKey var id: Int =0,
    @ColumnInfo(name="plant_type_name") var type:String ="",
    @ColumnInfo(name="plant_type_water")var water_time: String ="",
    @ColumnInfo(name="plant_type_details")var details: String = "",){
}

我试着用

@TypeConverter  or @SerializedName 

但这些注释似乎不可用也许我缺少了一个库?

这是我的gradle文件:

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    //Room database
    implementation "androidx.room:room-runtime:2.3.0"
    implementation "androidx.room:room-ktx:2.3.0"
    kapt "androidx.room:room-compiler:2.3.0"
    //coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2'
    //Viewmodel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
    //LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
    //ui
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    //navigation
    implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
    implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    //views
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    //testing
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

我将感谢你的帮助!

共有1个答案

裘光启
2023-03-14

如果您计划插入,则更容易:

@Entity
data class Plant(

    @PrimaryKey  var id:Long,
    @ColumnInfo (name="plant_name") var name: String,
    @ColumnInfo(name ="plant_type") var type: Plant_Category,
    @ColumnInfo(name= "plant_image") var image: Int,
    @ColumnInfo(name="plant_type_name") var type:String ="",
    @ColumnInfo(name="plant_type_water")var water_time: String ="",
    @ColumnInfo(name="plant_type_details")var details: String = "",


    ) {

}

如果您想为类别设置一个特定的实体,在其中插入新的工厂类型,您也可以使用此实体。

@Entity
data class Plant_Category(

    @PrimaryKey var id: Int =0,
    @ColumnInfo(name="plant_type_name") var type:String ="",
    @ColumnInfo(name="plant_type_water")var water_time: String ="",
    @ColumnInfo(name="plant_type_details")var details: String = "",){
}

这将更容易管理:)

 类似资料: