【发布时间】:2021-08-07 18:07: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,
) {
}
这是 PlantCategory 类:
@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'
}
感谢您的帮助!
【问题讨论】:
-
@TypeConverter在androidx.room:room-common中定义。您从androidx.room:room-runtime得到传递依赖。 -
@CommonsWare 好的我试试
-
@CommonsWare
@SerializedName怎么样?我认为它仍然需要序列化名称,因为它仍然给我同样的错误。 -
@SerializedName不是房间的一部分。我看到注释最常见的地方是使用 Gson (com.google.gson.annotations.SerializedName) 将对象转换为 JSON 或从 JSON 转换对象。您可以在@TypeConverter中使用 Gson 将某些类型转换为String或从String转换以存储在数据库中,但是还有其他 JSON 库(例如 Moshi)和其他实现@TypeConverter. -
啊,谢谢你的回答我设法用
@Embedded消除了错误
标签: android android-studio kotlin android-room