使用Room DAO改装Kotlin将数据更新到服务器时失败

问题描述

我想将数据更新到服务器,但是当我上传数据时,发生了数据重新创建的情况。我正在使用DAO访问我的数据库,并进行了改造以从服务器获取数据 这是我的代码

我的DAO

import android.arch.persistence.room.*

@Dao
interface WoodProductDao {
@Query("select * from wood_product where access_id = :accessId and tree_id = :treeId and updated < 3 and deleted = 0")
fun getWoodProducts(accessId: Int,treeId: Int): List<WoodProductData>

@Query("select * from wood_product where access_id = :accessId and tree_id = :treeId")
fun getAllWoodProducts(accessId: Int,treeId: Int): List<WoodProductData>

@Query("select * from wood_product where access_id = :accessId and tree_id = :treeId and log_number = :logNumber")
fun getWoodProduct(accessId: Int,treeId: Int,logNumber: String): WoodProductData?

@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveWoodProduct(product: WoodProductData)

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun updateWoodProduct(product: WoodProductData)

@Update
fun updatedWoodProduct(product: WoodProductData)

@Query("select count(tree_id) from  wood_product where access_id = :accessId and tree_id = :treeId and updated < 3 group by tree_id")
fun getTreeProductCount(accessId: Int,treeId: Int): Int

@Query("select distinct order_id from wood_product where access_id = :accessId and (updated = 1 or updated = 2 or updated = 3)")
fun getUpdatedProductOrderIds(accessId: Int): List<Int>

@Query("select * from wood_product where access_id = :accessId and order_id = :orderId and (updated = 1 or updated = 2 or updated = 3)")
fun getUpdatedProductsByOrderId(accessId: Int,orderId: Int): List<WoodProductData>

@Query("select count(tree_id) from (select distinct tree_id from wood_product where access_id = :accessId and (updated > 0 and updated < 4))")
fun getUpdatedTreeIdCount(accessId: Int): Int

@Query("delete from wood_product where access_id = :accessId and order_id = :orderId and updated = 5")
fun deleteProductByOrderId(accessId: Int,orderId: Int)

@Query("select * from wood_product where access_id = :accessId and order_id = :orderId and updated = 5")
fun getDeletedProductsByOrderId(accessId: Int,orderId: Int): List<WoodProductData>

@Delete
fun deleteProduct(product: WoodProductData)}

存储库

class WoodProductInteractor(
val woodProductRepository: WoodProductRepository,val treeRepository: TreeRepository,val preferenceService: PreferenceService){


suspend fun getWoodProducts(treeId: Int): List<WoodProduct> {
    val accessId = preferenceService.accessId
    return woodProductRepository.getWoodProducts(accessId,treeId)
}

suspend fun getAllWoodProducts(treeId: Int): List<WoodProduct> {
    val accessId = preferenceService.accessId
    return woodProductRepository.getAllWoodProducts(accessId,treeId)
}

suspend fun getWoodProduct(treeId: Int,logNumber: String): WoodProduct? {
    val accessId = preferenceService.accessId
    return woodProductRepository.getWoodProduct(accessId,treeId,logNumber)
}

suspend fun deleteWoodProduct(product: WoodProduct) {
    val accessId = preferenceService.accessId
    if (product.updated == 2) {
        woodProductRepository.updatedWoodProduct(accessId,product.copy(updated = 4))
    } else {
        woodProductRepository.updatedWoodProduct(accessId,product.copy(updated = 3))
    }
    Log.d("setelah","didelete: $product")
}


suspend fun saveWoodProduct(product: WoodProduct) {
    val accessId = preferenceService.accessId
    val newProduct = product.copy(createdBy = accessId,updated = max(1,product.updated))
    woodProductRepository.updateWoodProduct(accessId,newProduct)
}
suspend fun updatedWoodProduct(product: WoodProduct) {
    val accessId = preferenceService.accessId
    val newProduct = product.copy(createdBy = accessId,product.updated))
    woodProductRepository.updatedWoodProduct(accessId,newProduct)}

这是activity.kt

class EditProductActivity : AppCompatActivity(),CoroutineScope {
companion object {
    const val paramTreeId = "param_tree_id"
    const val paramLogNumber = "param_log_number"
    const val paramOrderId = "param_order_id"
    const val paramOrderNum = "param_order_num"
}

private lateinit var job: Job
override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory

private val vm: EditProductViewModel by lazy {
    ViewModelProviders.of(this,viewModelFactory).get(EditProductViewModel::class.java)
}

private lateinit var diameterView: EditText
private lateinit var lengthView: EditText
private lateinit var rejectView: Spinner
private lateinit var ambilView: Spinner
private lateinit var pecahView: Spinner
private lateinit var lubangView: Spinner
private lateinit var pinholeView: Spinner
private lateinit var belimbingView: Spinner
private lateinit var toolbar: Toolbar

private var treeId = -1
private var orderId = -1
private var logNumber: String? = null
private var orderNum = ""


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    job = Job()
    AndroidInjection.inject(this)
    treeId = intent.getIntExtra(paramTreeId,-1)
    orderId = intent.getIntExtra(paramOrderId,-1)
    logNumber = intent.getStringExtra(paramLogNumber)
    orderNum = intent.getStringExtra(paramOrderNum)

    coordinatorLayout {
        relativeLayout {
            toolbar {
                id = R.id.toolbar
                backgroundColor = ContextCompat.getColor(context,R.color.colorPrimaryDark)
                setTitleTextColor(Color.WHITE)
                setSubtitleTextColor(Color.WHITE)
            }.lparams {
                alignParentTop()
                width = matchParent
                height = wrapContent
            }
            verticalLayout {
                tableLayout {
                    setColumnStretchable(1,true)
                    tableRow {
                        textView("Diameter (cm) ") {
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }

                        diameterView = editText {
                            typeface = boldFace
                            textColor = Color.BLACK
                            textSize = regularText
                            inputType = InputType.TYPE_CLASS_NUMBER
                            nextFocusForwardId = R.id.input_length
                        }
                    }
                    tableRow {
                        textView("Panjang (cm) ") {
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }

                        lengthView = editText {
                            id = R.id.input_length
                            typeface = boldFace
                            textColor = Color.BLACK
                            textSize = regularText
                            inputType = InputType.TYPE_CLASS_NUMBER
                            nextFocusForwardId = R.id.input_reject_status
                        }
                    }
                    tableRow {
                        textView("Kualitas") {
                            id = R.id.input_reject_status
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }
                        rejectView = spinner {
                            adapter = ArrayAdapter<String>(
                                context,android.R.layout.simple_spinner_dropdown_item,arrayOf("Super","Reject","Non Super")
                            )
                        }
                    }
                    tableRow {
                        textView("Status Ambil ") {
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }
                        ambilView = spinner {
                            adapter = ArrayAdapter<String>(
                                context,arrayOf("Tidak","Ya")
                            )
                        }
                    }
                    tableRow {
                        textView("Pecah ") {
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }
                        pecahView = spinner {
                            adapter = ArrayAdapter<String>(
                                context,arrayOf(
                                    "Tidak pecah","Pecah sudah dipotong","Pecah belum dipotong"
                                )
                            )
                        }
                    }
                    tableRow {
                        textView("Lubang Gerek ") {
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }
                        lubangView = spinner {
                            adapter = ArrayAdapter<String>(
                                context,arrayOf(
                                    "Tidak lubang","Lubang sudah dipotong","Lubang belum dipotong"
                                )
                            )
                        }
                    }
                    tableRow {
                        textView("Pinhole ") {
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }
                        pinholeView = spinner {
                            adapter = ArrayAdapter<String>(
                                context,arrayOf("Tidak ada","Ada")
                            )
                        }
                    }
                    tableRow {
                        textView("Belimbing/Banir ") {
                            typeface = regularFace
                            textColor = Color.BLACK
                            textSize = regularText
                        }
                        belimbingView = spinner {
                            adapter = ArrayAdapter<String>(
                                context,arrayOf(
                                    "Tidak ada","Belimbing sudah dipapras","Belimbing belum dipapras"
                                )
                            )
                        }
                    }
                }.lparams(matchParent,wrapContent)
            }.lparams(matchParent,wrapContent) {
                below(R.id.toolbar)
                margin = dip(8)
            }
            linearLayout {
                val cancelButton = button("Batal"){
                    backgroundColor = Color.RED
                    typeface = boldFace
                    textSize = buttonText
                    textColor = Color.WHITE
                }.lparams(dip(0),wrapContent) { weight = 1f }
                cancelButton.setOnClickListener {
                    finish()
                }
                val saveButton = button("Simpan"){
                    backgroundColor = BUTTON_EMERALD
                    typeface = boldFace
                    textSize = buttonText
                    textColor = Color.WHITE
                }.lparams(dip(0),wrapContent) { weight = 1f }
                saveButton.setOnClickListener {
                    saveProduct()
                }
            }.lparams(matchParent,wrapContent) {
                alignParentBottom()
            }
        }.lparams(matchParent,matchParent)
    }

    toolbar = findViewById(R.id.toolbar)
    toolbar.title = if(logNumber == null) "Tambah Kayu" else "Edit Kayu"
    toolbar.subtitle = logNumber
    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp)
    toolbar.setNavigationOnClickListener {
        onBackPressed()
    }

    vm.productData.observe(this,Observer(::onProductUpdate))
    launch {
        vm.loadProduct(orderId,orderNum,logNumber)
    }
}


private fun onProductUpdate(product: WoodProduct?) {
    product ?: return
    toolbar.subtitle = product.logNumber
    diameterView.setText(product.diameter)
    lengthView.setText(product.length)
    ambilView.setSelection(product.isTaken)
    rejectView.setSelection(product.rejectStatusPetani)
    pecahView.setSelection(product.statusPecah)
    lubangView.setSelection(product.lubangGerek)
    pinholeView.setSelection(product.pinHole)
    belimbingView.setSelection(product.belimbing)

}

private fun saveProduct() {
    val newdiameter = diameterView.text.toString()
    val newLength = lengthView.text.toString()
    val newReject = rejectView.selectedItemPosition
    val newAmbil = ambilView.selectedItemPosition
    val newPecah = pecahView.selectedItemPosition
    val newGerek = lubangView.selectedItemPosition
    val newPinhole = pinholeView.selectedItemPosition
    val newBelimbing = belimbingView.selectedItemPosition
    if (newdiameter.isBlank() || newLength.isBlank()) {
        alert {
            title = "Input tidak lengkap"
            isCancelable = false
            message = "Input data tidak lengkap,harap periksa kembali."
            okButton { it.dismiss() }
        }.show()
    } else {
        launch {
            vm.saveProduct(newdiameter,newLength,newReject,newAmbil,newPecah,newGerek,newPinhole,newBelimbing)
            Log.d("status","ambil = $newAmbil")
            finish()
        }
    }
}}

这是我的视图模型

class EditProductViewModel @Inject constructor(
val productInteractor: WoodProductInteractor
) : ViewModel() {
val productData = MutableLiveData<WoodProduct>()


private val numberFormat = DecimalFormat("###.##")

suspend fun loadProduct(orderId: Int,orderNum: String,logNumber: String?) {
    val product = if (logNumber != null) GlobalScope.async(Dispatchers.IO) {
        productInteractor.getWoodProduct(treeId,logNumber)
    }.await() else {
        val logSequenceNumber = GlobalScope.async(Dispatchers.IO) {
            productInteractor.getAllWoodProducts(treeId)
        }.await().size + 1
        val newLogNumber = GlobalScope.async(Dispatchers.IO) {
            productInteractor.createLogNumber(
                treeId,logSequenceNumber
            )
        }.await()
        WoodProduct(
            null,orderId,logSequenceNumber,newLogNumber,"",1,2
        )
    }
    GlobalScope.launch(Dispatchers.Main) {
        productData.value = product
    }
}

suspend fun saveProduct(
    newDiameter: String,newLength: String,newReject: Int,newAmbil: Int,newPecah: Int,newGerek: Int,newPinhole: Int,newBelimbing: Int
) {
    val product = productData.value ?: return
    val newCircumference = numberFormat.format(newDiameter.toDouble() * 3.14)
    val newProduct = productData.value?.copy(
        diameter = newDiameter,length = newLength,circumference = newCircumference,rejectStatusPetani = newReject,isTaken = newAmbil,statusPecah = newPecah,lubangGerek = newGerek,pinHole = newPinhole,belimbing = newBelimbing
    )
    runBlocking(Dispatchers.IO){
        if (newProduct!=null){
            if (product.updated==2) productInteractor.saveWoodProduct(newProduct)
            else productInteractor.updatedWoodProduct(newProduct)
        }
    }

有人可以帮助我吗?因为我不是从nol创建此代码,所以我只是从新公司继续此代码,而我是kotlin的新手 谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...