1 回答
TA贡献2051条经验 获得超10个赞
要根据现有值将值写入实时数据库,您需要使用事务。
您的交易的基本代码如下所示:
DatabaseReference balanceRef = FirebaseDatabase.getInstance().getReference("/Users/"+ user_id +"/Balance");
Long delta = 50l;
balanceRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Long balance = mutableData.getValue(Long.class);
if (balance == null) {
mutableData.setValue(delta);
}
else {
Long amount = mutableData.getValue(Long.class);
amount = amount + delta;
mutableData.setValue(amount);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "balanceTransaction:onComplete:" + databaseError);
}
});
添加回答
举报