Android Firebase数据库事务 [英] Android Firebase database transaction

查看:67
本文介绍了Android Firebase数据库事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ATNRef= FirebaseDatabase.getInstance().getReference("AvailableTokenNumber");
                ATNRef.runTransaction(new Transaction.Handler() {
                    @Override
                    public Transaction.Result doTransaction(MutableData mutableData) {

                        if (mutableData.getValue(int.class ) == 0){
                            mutableData.setValue(2);
                            data.tokenNo = 1;
                            return Transaction.success(mutableData);

                        }else {
                            data.tokenNo=mutableData.getValue(int.class);
                            mutableData.setValue(data.tokenNo + 1);
                            return Transaction.success(mutableData);
                        }
                    }

首次运行代码时,data.tokenNo的值为0. 之后,它将根据数据库值正确更新.

Whenever the code is run for first time, value of data.tokenNo is 0. After that it is updating correctly as per the database value.

我无法弄清楚是什么原因使应用程序/代码的每次首次运行时data.token = 0.

I am not able to figure it out what makes the value of data.token = 0 on every first run of the app/code.

推荐答案

您应该期望事务中的可用数据的初始快照在首次执行期间可以为null.请注意文档:

You should be expecting that the initial snapshot of data available in your transaction could be null during its first execution. Note this from the documentation:

注意:由于doTransaction()被多次调用,因此必须 能够处理空数据.即使您的数据库中已有数据 远程数据库,在事务处理时可能未在本地缓存 函数运行,结果为空.

Note: Because doTransaction() is called multiple times, it must be able to handle null data. Even if there is existing data in your remote database, it may not be locally cached when the transaction function is run, resulting in null for the initial value.

也在 javadoc 中它说:

此方法可能会被当前方法多次调用 数据在此位置.

This method will be called, possibly multiple times, with the current data at this location.

预计第一次运行处理程序时,它将处理一个空数据库.然后,当已知数据(如果有)时,您也应该准备处理这种情况.如果您不想在该位置没有数据(或未知数据)的地方做任何事情,只需返回一个成功的Transaction,而无需更改mutableData.

Expect that the first time your handler is run, it will be dealing with an empty database. Then, when the data there is known (if any), you should be prepared to handle that case also. If you don't want to do anything where there is no data (or unknown data) at the location, simply return a successful Transaction with no changes to mutableData.

这篇关于Android Firebase数据库事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆