You need to enable JavaScript to run this app. 使用Retrofit删购物车商品后RecyclerView Adapter未即时更新,onResume无效
优惠活动
大模型
产品
解决方案
定价
更多

使用Retrofit删购物车商品后RecyclerView Adapter未即时更新,onResume无效

Android购物车删除商品后列表不即时刷新问题

问题场景

开发Android购物车页面功能时,通过自定义接口传递待删除商品ID,结合Retrofit完成后端接口交互,遇到删除操作后列表无法即时刷新的问题。

原有Activity核心实现代码如下:

@Override
protected void onResume() {
    super.onResume();
    getCartList();
}

private void getCartList() {
    showProgressDialog();
    Call<List<CartList>> call = api.getCartList(1);
    call.enqueue(new Callback<List<CartList>>() {
        @Override
        public void onResponse(Call<List<CartList>> call, Response<List<CartList>> response) {
            cartLists = response.body();
            if (cartLists.size() == 0) {
                tvCartEmpty.setVisibility(View.VISIBLE);
                progressDialog.cancel();
            } else {
                addToCartAdapter.setData(cartLists);
                productList.setAdapter(addToCartAdapter);
                progressDialog.cancel();
            }
        }

        @Override
        public void onFailure(Call<List<CartList>> call, Throwable t) {
            Toast.makeText(AddToCartActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public void deleteItemID(int id) {
    Call<CartList> deleteCall = api.deleteCartItem(id);
    deleteCall.enqueue(new Callback<CartList>() {
        @Override
        public void onResponse(Call<CartList> call, Response<CartList>> response) {
            Log.d(TAG, "deleteItem by id" + response.code());
            onResume();
        }

        @Override
        public void onFailure(Call<CartList> call, Throwable t) {
            Log.d(TAG, t.getMessage());
        }
    });
}

异常表现

  • 最后一项商品的后端删除请求可正常返回成功
  • 列表界面不会即时同步更新删除后的状态
  • 即使在删除接口的成功回调中手动调用onResume()方法,仍需重新打开该Activity才能看到更新后的正确结果

最初排查阶段,曾认为接口请求、Adapter的逻辑无问题,如需进一步定位需要补充更多模块代码,最终自行定位到问题根因。

问题根因

购物车列表获取接口的回调分支存在逻辑遗漏:当删除完最后一项商品、接口返回空列表时,原有代码仅控制了空状态布局的显示,没有给Adapter同步绑定空列表数据,也未同步更新购物车商品总数的文本,导致Adapter一直保留之前缓存的旧列表数据,无法触发界面刷新。

修复方案

在获取购物车列表接口的onResponse回调中,补全两个分支的处理逻辑:

  • 列表为空时:除了显示空状态布局,同步给Adapter设置空列表数据、将购物车商品总数文本更新为0 items
  • 列表非空时:除了给Adapter绑定列表数据,同步更新购物车商品总数的文本显示

修复后的回调代码如下:

@Override
public void onResponse(Call<List<CartList>> call, Response<List<CartList>> response) {
    cartLists = response.body();
    if (cartLists.size() == 0) {
        tvCartEmpty.setVisibility(View.VISIBLE);
        tvCartItems.setText("0 items");
        addToCartAdapter.setData(cartLists);
        progressDialog.cancel();
    } else {
        addToCartAdapter.setData(cartLists);
        productList.setAdapter(addToCartAdapter);
        tvCartItems.setText(cartLists.size() + " Items");
        progressDialog.cancel();
    }
}

内容的提问来源于stack exchange,提问作者Parth kabariya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 01:36:06