且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

(如果是,则)实时数据库中的问题检查编号等于或大于

更新时间:2022-05-03 03:23:50

要获取具有 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);

其中 money 变量对于递增操作可以是任何正数,对于递减操作可以是负数.除此之外,无需为简单的递增/递减操作运行事务.我们可以简单地使用较简单的新添加的 ServerValue.increment(value)选项.仅当我们需要首先读取属性的值时,才使用事务.

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.

如果将数据库中 money 属性的类型从String更改为number,这两种解决方案都将有效,仅 .因此,请进行以下更改:

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?

收件人:

money: 7 //No quotations marks