Update some specific field of an entity in android Room

前端 未结 7 1628
臣服心动
臣服心动 2020-11-29 16:45

I am using android room persistence library for my new project. I want to update some field of table. I have tried like in my Dao -

// Method 1         


        
7条回答
  •  萌比男神i
    2020-11-29 17:26

    We need the primary key of that particular model that you want to update. For example:

     private fun update(Name: String?, Brand: String?) {
        val deviceEntity = remoteDao?.getRemoteId(Id)
        if (deviceEntity == null)
            remoteDao?.insertDevice(DeviceEntity(DeviceModel = DeviceName, DeviceBrand = DeviceBrand))
        else
            DeviceDao?.updateDevice(DeviceEntity(deviceEntity.id,remoteDeviceModel = DeviceName, DeviceBrand = DeviceBrand))
    }
    

    In this function, I am checking whether a particular entry exists in the database if exists pull the primary key which is id over here and perform update function.

    This is the for fetching and update records:

    @Query("SELECT * FROM ${DeviceDatabase.DEVICE_TABLE_NAME} WHERE ${DeviceDatabase.COLUMN_DEVICE_ID} = :DeviceId LIMIT 1")
    
    fun getRemoteDeviceId(DeviceId: String?): DeviceEntity
    
    
    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun updatDevice(item: DeviceEntity): Int
    

提交回复
热议问题