You need to enable JavaScript to run this app. Retrofit结合ViewModel实现购物车Spinner编辑功能的取值异常排查
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit结合ViewModel实现购物车Spinner编辑功能的取值异常排查

问题根因定位
  • 核心提交参数构造错误:非ViewModel的正常实现中,提交到editCart接口的quantity参数,是仅包含用户选中值的单元素数组arrayOf(country[position]);但ViewModel版本的loadEdit()方法,直接把存储全量可选值的数组country = [1,2,3,4,5,6,7,8]作为完整quantity参数传给接口。后端接收到多元素数组时,按业务规则取数组最后一个元素8作为更新值,因此无论前端选择什么数值,最终写入数据库的都是8。
  • 参数传递链路断裂:Adapter的回调接口EditItem(spinnerSelectedPosition, productId)在Activity实现层,没有把用户选中的具体数量值传递给ViewModel,仅传递了商品ID,导致ViewModel完全不知道当前应该提交哪个数量值。
  • 无效赋值逻辑干扰:Activity中viewModel.country[position] = country[position]的代码没有实际作用,两个数组内容完全一致;且ViewModel持有的country数组是所有RecyclerView条目共享的全局变量,单条目Spinner的选择操作会篡改全局数组值,进一步加剧取值混乱。
  • 缺少Spinner初始化回显的判断逻辑:Adapter执行setSelection做数量回显时,会自动触发onItemSelected回调,发起无意义的接口请求,导致状态错乱。
修复方案

1. 调整ViewModel的参数定义与提交逻辑

  • 新增独立字段存储当前选中的商品数量,不再复用全局可选值数组作为提交参数:
// 存储当前待提交的选中数量
val selectedQuantity = MutableLiveData<Int>()

// 重构loadEdit方法,构造正确的单元素数组提交
fun loadEdit() {
    val productId = product_id.value!!.trim().toInt()
    val quantity = selectedQuantity.value ?: 1
    val token = SharedPrefManager.getInstance(getApplication()).user.access_token

    // 保持和非ViewModel实现一致,仅提交单元素数量数组
    RetrofitClient.instance.editCart(token, productId, arrayOf(quantity))
        .enqueue(object : Callback<DeleteResponse> {
            // 原有回调逻辑完全保留,无需修改
        })
}
  • ViewModel中的country数组仅作为Spinner的选项数据源使用,不参与接口提交逻辑。

2. 修正Activity的回调传参逻辑

  • 重写EditItem方法的参数传递链路,把用户实际选中的数量值同步给ViewModel:
override fun EditItem(spinnerSelectedPosition: Int, productId: Int) {
    // 传入当前操作的商品ID
    viewModel.product_id.value = productId.toString()
    // 传入Spinner选中位置对应的真实数量值
    viewModel.selectedQuantity.value = country[spinnerSelectedPosition]
    // 发起编辑请求
    viewModel.loadEdit()

    // 原有结果观察逻辑完全保留
    viewModel.Results.observe(this) { result ->
        when (result) {
            CartViewModel.Result.Missing -> Toast.makeText(applicationContext, "product is missing", Toast.LENGTH_LONG).show()
            CartViewModel.Result.Success -> {
                finish()
                val intent = Intent(applicationContext, AddToCart::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                startActivity(intent)
                overridePendingTransition(0, 0)
            }
            else -> Toast.makeText(applicationContext, "hello", Toast.LENGTH_LONG).show()
        }
    }
}
  • 删掉原实现中viewModel.country[position] = country[position]的无效代码。

3. 规避Spinner初始化回显的重复触发问题

  • 在CartAdapter中增加标记变量,区分初始化回显和用户主动选择的触发场景:
// Adapter类内新增标记
private var isInitialSelection = true
  • 修改Spinner回调逻辑,在初始化回显阶段不触发接口请求:
// 回显之前复位标记
isInitialSelection = true
holder.spin.setSelection(dataList?.get(position)?.quantity!! - 1, false)

holder.spin.setOnItemSelectedListener(object : OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>, view: View, position1: Int, id: Long) {
        // 初始化回显阶段跳过,不发起请求
        if (isInitialSelection) {
            isInitialSelection = false
            return
        }
        progressDialog.show()
        val productId = dataList?.get(position)!!.product.id
        itemClick?.EditItem(position1, productId!!.toInt())
    }

    override fun onNothingSelected(parent: AdapterView<*>?) {
        // 原有逻辑保留
    }
})

内容的提问来源于stack exchange,提问作者android dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.20 05:15:06