无法更新会议室数据库中的对象

时间:2019-10-10 19:27:48

标签: android kotlin android-room

我想通过ID更新“房间”中的对象,但是它不起作用。

这是我的DAO课

 @Query("UPDATE greeting SET id =:id")
    abstract fun updateGreetingByID(id: String)

这是我的DBHelper

  fun updateGreetingByID(id: String) {
        Thread { dataBase.greetingDao().updateGreetingByID(id) }.start()
    }

我的模特


@Entity(tableName = "greeting")
class GreetingModel(
    id: String? = "",
    greetingCategory: String = "",
    isFavourite: Boolean = false,
    position: Int = 0
) : Parcelable {

    @PrimaryKey(autoGenerate = true)
    var _id: Int = 0

    @ColumnInfo(name = "id")
    var id: String? = null

    @ColumnInfo(name = "greetingCategory")
    var greetingCategory: String? = null

    @ColumnInfo(name = "isFavourite")
    var isFavourite: Boolean? = null

    @ColumnInfo(name = "imageId")
    var imageId: ByteArray? = null

    @ColumnInfo(name = "position")
    var position: Int = 0

    @ColumnInfo(name = "saved")
    var saved: Int = 0

    constructor(parcel: Parcel) : this(
    ) {
        _id = parcel.readInt()
        id = parcel.readString()
        greetingCategory = parcel.readString()
        isFavourite = parcel.readValue(Boolean::class.java.classLoader) as? Boolean
        imageId = parcel.createByteArray()
        position = parcel.readInt()
        saved = parcel.readInt()
    }


    init {
        this.id = id
        this.greetingCategory = greetingCategory
        if (position != null) {
            this.position = position
        }
        this.isFavourite = isFavourite
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeInt(_id)
        parcel.writeString(id)
        parcel.writeString(greetingCategory)
        parcel.writeValue(isFavourite)
        parcel.writeByteArray(imageId)
        parcel.writeInt(position)
        parcel.writeInt(saved)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<GreetingModel> {
        override fun createFromParcel(parcel: Parcel): GreetingModel {
            return GreetingModel(parcel)
        }

        override fun newArray(size: Int): Array<GreetingModel?> {
            return arrayOfNulls(size)
        }
    }

}

idval id = UUID.randomUUID().toString()的地方

我想在用户单击“收藏夹”按钮时更新对象

 val greetingModel = GreetingModel()
                    greetingModel.isFavourite = true
                    greetingModel.greetingCategory = " "
                    greetingModel.position = postImage


                    greetingModel.id?.let { helper.updateGreetingByID(greetingModel.id!!) }

我的update方法不起作用。希望你会帮助!

1 个答案:

答案 0 :(得分:1)

您的问题是,您正在尝试根据新构造的Greeting进行更新,该问候的id是使用默认值(无参数构造函数)构造Greeting时ID设置为的任何值。

解决方法是在执行更新之前检索被单击的Greeting的特定ID,并将该ID设置为该值。