fungous_bread
fungous_bread

Reputation: 29

How to return a value from OnCompleteListener while creating user with email and password in Firestore?

The code which I am trying to write is

private String val;
    public String checkEmail(){

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        db.collection("cities").whereEqualTo("cities", "Boston").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()){
                            val = "City exists";
                        }else{
                            val = "City does not exist";
                        }
                    }
                });
        return val;
    }


This code returns val as null instead of the values. How can this problem be solved?

Upvotes: 1

Views: 1650

Answers (1)

Erwin Kurniawan A
Erwin Kurniawan A

Reputation: 1008

I'm sure this because the call is async, change your method to non return value (void) and create an interface callback to return value when the call is complete. Try this..

interface CityCallback {
     void isCityExist(boolean exist);
}

public void checkEmail(CityCallback cityCallback){
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    db.collection("cities").whereEqualTo("cities", "Boston").get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()){
                        cityCallback.isCityExist(true);
                    }else{
                        cityCallback.isCityExist(false);
                    }
                }
            });
}

to call the method it will be like this

checkEmail(new CityCallback {
      @Override
      public void isCityExist(boolean exist) {
           if (exist) {
              // set the value of variable val or anything
           } else {
              // set the value of variable val or anything
           }
      }
});

i hope it help you

Upvotes: 4

Related Questions