(if, else) question check number equal or greater in Realtime database

huangapple go评论107阅读模式
英文:

(if, else) question check number equal or greater in Realtime database

问题

请注意,由于您要求仅返回翻译后的内容,以下是您提供的代码段的翻译:

如何实现 if-else 来检查货币字段的值是否等于或大于代码中预定义的值),并在实时数据库的货币字段上进行检查只有在此验证运行后代码才会执行我进行了网络搜索但我搜索到的所有方法在实现方面都没有成功

ref.child("users").child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
                    .child("users").child(user.getUid()).child("money");

            ref.runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(MutableData mutableData) {
                    Object currentMoney = mutableData.getValue();
                    int totalMoney = 0;
                    if (currentMoney == null) {
                        totalMoney = moneyToRemove;
                    } else {
                        totalMoney = Integer.parseInt(String.valueOf(currentMoney)) - moneyToRemove;
                    }

                    mutableData.setValue(totalMoney);
                    return Transaction.success(mutableData);
                }

                @Override
                public void onComplete(DatabaseError databaseError, boolean b,
                                       DataSnapshot dataSnapshot) {
                    // 交易完成
                }
            });
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // 取消操作
    }
});

数据库结构见上方图示链接。

英文:

How can I implement if-else to check if the value of the money field is equal or greater (pre defined value in code) checking on the Realtime database money field? Only after this verification runs the code? I did a web search but all the methods I have searched but none were successful in the implementation.

ref.child("users").child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
.child("users").child(user.getUid()).child("money");
ref.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Object currentMoney = mutableData.getValue();
int totalMoney = 0;
if (currentMoney == null) {
totalMoney = moneyToRemove;
} else {
totalMoney = Integer.parseInt(String.valueOf(currentMoney)) - moneyToRemove;
}
mutableData.setValue(totalMoney);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
}
});

Db structure

(if, else) question check number equal or greater in Realtime database

答案1

得分: 0

获取所有money属性值大于或等于7的用户,你应该使用类似下面的查询代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query moneyQuery = usersRef.orderByChild("money").startAt(7);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            ds.child("money").getRef().setValue(ServerValue.increment(money));
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //不要忽视潜在的错误!
    }
};
moneyQuery.addListenerForSingleValueEvent(valueEventListener);

然而,如果你只想对已登录用户执行此操作,请使用以下代码:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (ds.child("money").getValue(Long.class) >= 7) { 
            dataSnapshot.child("money").getRef().setValue(ServerValue.increment(money));
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //不要忽视潜在的错误!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

在这两种情况下,money变量可以是任何正数以进行增加操作,或者是负数以进行减少操作。除此之外,在简单的增加/减少操作中无需运行事务。我们可以简单地使用新增的ServerValue.increment(value)选项。事务仅在我们需要先读取属性值时才会使用。

只有在将数据库中money属性的类型从字符串更改为数字后,这两种解决方案才会生效。所以请进行以下更改:

从:

money: "7" //注意引号

到:

money: 7 //没有引号
英文:

To get all users that have the value of money property greater than or equal to 7 for example, you should definitely use a query that looks like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query moneyQuery = usersRef.orderByChild("money").startAt(7);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.child("money").getRef().setValue(ServerValue.increment(money));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
moneyQuery.addListenerForSingleValueEvent(valueEventListener);

However, if you only want to do this operation only on the logged-in user, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(ds.child("money").getValue(Long.class) >= 7)) { 
dataSnapshot.child("money").getRef().setValue(ServerValue.increment(money));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

In which the money variable can be any positive number for an increment operation or a negative number for a decrement operation. Besides that, there is no need to run a transaction for a simple increment/decrement operation. We can simply use the simpler newly added ServerValue.increment(value) option. The transactions are used only when we need to read the value of the property first.

Both solutions will work, only if you change the type of your money property in the database from String to number. So please do the following change:

money: "7" //See the quotations marks?

To:

money: 7 //No quotations marks

huangapple
  • 本文由 发表于 2020年10月1日 19:16:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64154276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定