Home > Enterprise >  How to Break For each in Android?
How to Break For each in Android?

Time:01-13

FirebaseFirestore.getInstance().collection("registration").addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(@Nullable QuerySnapshot value, @Nullable  FirebaseFirestoreException error) {
        for(DocumentSnapshot d:value){
       
            if(d.getId().equals(Name)){
                Toast.makeText(MainActivity.this, "User Name already exists", Toast.LENGTH_SHORT).show();
                break;
            }
            else{
                is_userExists = false;
            }
        }
    }
});

I want to break the foreach loop but the code isnt working properly

CodePudding user response:

Use return keyword instead of break;

FirebaseFirestore.getInstance().collection("registration").addSnapshotListener(new EventListener<QuerySnapshot>() {
                        @Override
                        public void onEvent(@Nullable QuerySnapshot value, @Nullable  FirebaseFirestoreException error) {
                            for(DocumentSnapshot d:value){
                           
                                if(d.getId().equals(Name)){
                                    Toast.makeText(MainActivity.this, "User Name already exists", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                else{
                                    is_userExists = false;
                                }
                            }
                        }
                    });

CodePudding user response:

It may be more logical to do this operation with a void method and return instead of break.

CodePudding user response:

Your Break should work as you want, nothing wrong with it.

What could be happening here is one of the following:

  1. d.getId().equals(Name) results in false because they are not equal
  2. d.getId() results in NullPointerException because d was not constructed earlier
  3. onEvent is not even called...

In this answer I assume your code compiles.

  •  Tags:  
  • Related