我的循环一直在运行一个特定的方法,我希望它只运行一次。

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

My loop keeps running a particular method which i want to run once

问题

for (DataSnapshot datasnapshot : snapshot.getChildren()) {
    if (datasnapshot.child("email").getValue().toString().equals(Prevalent.currentOnlineUser.getEmail())) {
        continue;
    }
    if (datasnapshot.child("username").getValue().toString().equals(Prevalent.currentOnlineUser.getUsername())) {
        continue;
    }
    if (datasnapshot.child("username").getValue().toString().equals(textUsername)) {
        Toast.makeText(Profile_Page_Activity.this, "Username already exists, try again", Toast.LENGTH_SHORT).show();
    } else {
        if (datasnapshot.child("email").getValue().toString().equals(textemail)) {
            Toast.makeText(Profile_Page_Activity.this, "E-mail id taken please provide another one", Toast.LENGTH_SHORT).show();
        } else {
            uploadprofileimage();
        }
    }
}

The uploadprofileimage() is the method I am trying to run ONCE given certain conditions.

英文:

I am trying to save data into firebase database but i put the method that actually saves the data in a if..else statement and the if...else statement in a for loop because i need to check for different conditions before running the method, there are series of if statements in the for loop, but I am starting to get really confused bacause the method keeps running and i don't see why, please help

for(DataSnapshot datasnapshot : snapshot.getChildren()){
    if(datasnapshot.child("email").getValue().toString().equals(Prevalent.currentOnlineUser.getEmail())){continue;}
    if(datasnapshot.child("username").getValue().toString().equals(Prevalent.currentOnlineUser.getUsername())){continue;}
    if(datasnapshot.child("username").getValue().toString().equals(textUsername)){
        Toast.makeText(Profile_Page_Activity.this, "Username already exists, try again", Toast.LENGTH_SHORT).show();
    }else{
        if(datasnapshot.child("email").getValue().toString().equals(textemail)){
            Toast.makeText(Profile_Page_Activity.this, "E-mail id taken please provide another one ", Toast.LENGTH_SHORT).show();
        }else{
            uploadprofileimage();
        }
    }
}

The uploadprofileimage() is the method i am trying to run ONCE given certain conditions.

答案1

得分: 1

你应该在执行完你的函数后添加一个 break。就像这样:

else{
  uploadprofileimage();
  break;
}

否则,循环会一直运行,因为没有任何停止它的东西。

英文:

You should add a break after executing your function. Something like this:

else{
  uploadprofileimage();
  break;
}

Else, the loop would just keep running since there is nothing stopping it.

huangapple
  • 本文由 发表于 2020年9月12日 17:53:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63859059.html
匿名

发表评论

匿名网友

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

确定