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

僤鯓⒐⒋嵵緔 提交于 2021-02-11 04:52:23

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/64154276/if-else-question-check-number-equal-or-greater-in-realtime-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!