You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase实时数据库计数更新异常:删除操作未递减数值

问题分析与解决方案

你遇到的删除操作后计数未递减的问题,可从以下几个方向排查并解决:

1. 异步操作顺序冲突

当前代码在调用PosteDes()后立即执行页面跳转和Activity销毁,而Firebase事务是异步执行的,这会导致计数更新操作还未完成就被中断,无法写入数据库。

解决方法:将页面跳转逻辑移到事务的onComplete回调中,确保计数更新完成后再执行跳转:

修改DeleteData中的存储删除成功回调:

storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void unused) {
        // 先确保数据库数据删除完成
        reference.child(key).removeValue().addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                // 数据删除成功后再执行计数递减
                PosteDes();
            } else {
                Toast.makeText(DetailClinic.this, "数据删除失败", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Failed to delete clinic data", task.getException());
            }
        });
    }
});

修改PosteDes的onComplete方法:

@Override
public void onComplete(DatabaseError error, boolean committed,
                       DataSnapshot currentData) {
    if (error != null) {
        Log.w(TAG, "Transaction failed:", error.toException());
        Toast.makeText(DetailClinic.this, "计数更新失败", Toast.LENGTH_SHORT).show();
    } else {
        Log.d(TAG, "Transaction committed. 最新计数: " + currentData.getValue(Integer.class));
        // 计数更新完成后再执行页面跳转
        Toast.makeText(DetailClinic.this, "已永久删除", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getApplicationContext(), HomeClinics.class));
        AnimationOut();
        finish();
    }
}

2. 确认事务是否被正确触发

先验证PosteDes()是否真的被调用,以及用户ID是否正确:

  • 在PosteDes()方法开头添加日志:
    private void PosteDes(){
        Log.d(TAG, "PosteDes method called");
        String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        Log.d(TAG, "Current user ID: " + userId);
        // ... 剩余代码
    }
    
  • 查看Logcat输出,确认方法被调用且userId与新增时一致。

3. 检查数据库权限

确保Firebase Realtime Database规则允许当前用户修改dbStatis/Clinics/[userId]节点,推荐设置如下(仅允许用户操作自己的计数):

{
  "rules": {
    "dbStatis": {
      "Clinics": {
        "$userId": {
          ".read": "$userId === auth.uid",
          ".write": "$userId === auth.uid"
        }
      }
    }
  }
}

4. 验证计数计算逻辑

在事务中添加日志,确认计数的读取和计算是否正确:

@Override
public Transaction.Result doTransaction(MutableData mutableData) {
    Integer currentValue = mutableData.getValue(Integer.class);
    Log.d(TAG, "Current count value: " + currentValue);
    if (currentValue == null) {
        currentValue = 0;
        Log.d(TAG, "Current value is null, set to 0");
    }
    int newValue = Math.max(0, currentValue - 1);
    Log.d(TAG, "New count value: " + newValue);
    mutableData.setValue(newValue);
    return Transaction.success(mutableData);
}

通过日志确认计数的递减逻辑是否正常执行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:20:16