java - Android studio/Firebase - 遇到无限循环试图获取数据

标签 java android firebase firebase-authentication

我正在尝试从我的 firebaseDB 中获取数据,但它一直在无限地进行,我不明白为什么。

问题:用户键入要汇款的邮件。我从数据库中提取所有用户,并将书面电子邮件与每个用户的电子邮件进行比较。如果电子邮件与用户匹配(电子邮件是唯一的),则在内部进行另一个数据库调用,获取收件人的余额。用户的余额已更新,收款人的余额也已更新。 问题是它不断减去发件人的金额,并不断地为收件人添加金额(通过单击一次)。

我知道这与异步执行有关,但我对编程太陌生,不知道如何解决。

有人可以帮忙吗?代码如下:

    public void sendTo(){

    final String receiverEmail = editTextReciever.getText().toString().trim();
    String amountHolder = ediTextAmount.getText().toString().trim();

    if(TextUtils.isEmpty(receiverEmail)){
        Toast.makeText(getApplicationContext(), "Enter an email", Toast.LENGTH_LONG).show();
        return;
    }
    if(TextUtils.isEmpty(amountHolder)){
        Toast.makeText(getApplicationContext(), "Enter an amount to send", Toast.LENGTH_LONG).show();
        return;
    }

    //If it has gotten this far, theres data in the editText (the editText can only contain numbers)
    final int amount = Integer.parseInt(amountHolder);

    //Looping through every user in the DB and checking if the typed email belong to any of the users in the DB
    FirebaseDatabase.getInstance().getReference("users").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                User user = snapshot.getValue(User.class);
                //If typed email matches a user in the db (emails are unique due to firebaseAuthentication), continue
                if(user.getEmail().equals(receiverEmail)){

                    recipientUid = snapshot.getKey();
                    if(accountBalance - amount >= 0 && uid != snapshot.getKey()){
                        //I have to fetch our the balance of the user i'm sending money to so I can add the amount to his balance
                        FirebaseDatabase.getInstance().getReference("Accounts/" + accountType).child(snapshot.getKey()).child("balance").addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                int balanceOfReceiver = Integer.parseInt(dataSnapshot.getValue().toString());
                                int updatedBalance = balanceOfReceiver + amount;
                                //The senders balance is updated
                                accountBalance = accountBalance - amount;
                                FirebaseDatabase.getInstance().getReference("Accounts/" + accountType).child(uid).child("balance").setValue(accountBalance);
                                //And the recipients balance is updated
                                FirebaseDatabase.getInstance().getReference("Accounts/" + accountType).child(recipientUid).child("balance").setValue(updatedBalance);
                            }
                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });
                    } else {
                        Toast.makeText(getApplicationContext(), "You can't overdraw or send money to yourself", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

最佳答案

您将 ValueEventListener 添加到用户引用中,并在数据发生变化时调用 onDataChange。 您减去金额并再次触发 onDataChange,然后进入循环。

在更改金额之前,您需要重新考虑您的代码结构或删除监听器。

这个

FirebaseDatabase.getInstance().getReference("Accounts/" + accountType).child(uid).child("balance").setValue(accountBalance);
FirebaseDatabase.getInstance().getReference("Accounts/" + accountType).child(recipientUid).child("balance").setValue(updatedBalance);

触发这个

public void onDataChange(@NonNull DataSnapshot dataSnapshot) 

关于java - Android studio/Firebase - 遇到无限循环试图获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528243/

相关文章:

java - 在 Spark Scala 中处理微秒

java - 如何使用java文档和类

android - 创建具有特定滚动动画效果的自定义圆形进度条

javascript - 构造函数中的变量在渲染前未定义但在渲染后可见

java - Firebase/Android : Get current user email

java - 如何在 Android 中为 TabActivity 更改设置动画?

android - 错误在路径 : DexPathList[[zip file 上找不到类 "com.example.i.MainActivity"

java - 为什么 Bitmap.getConfig() 返回 null?

javascript - Firebase JS - Firebase 无法插入 firestore

java - 如何在JavaFX中制作自定义LineChart控件?