0

this function return message it return null i need solution to return value thanks

public String saveData(final User user) {
        final String[] message = new String[1];
        firebaseAuth = FirebaseAuth.getInstance();
        firebaseAuth.createUserWithEmailAndPassword(user.getEmail().toString(), user.getPassword().toString())
                .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                    @Override
                    public void onSuccess(AuthResult authResult) {

                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                message[0] = "Fail" + e.getMessage();
            }
        });

        return message[0];
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user9213317
  • 33
  • 1
  • 5
  • You can also take a look at [this](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774). – Alex Mamo Oct 10 '18 at 08:36

1 Answers1

0

The problem is that firebaseAuth.createUserWithEmailAndPassword() is asynchronous operation - so onSuccess() and onFailure() callbacks will be triggered lately in the future. But you will return message[0] immediately after starting operation - that's why you get null result. To solve that problem you can pass callbacks as arguments to your function and handle result when that callbacks will be triggered. For example,

public void saveData(final User user, OnSuccessListener<AuthResult> success, OnFailureListener failure) {
    final String[] message = new String[1];
    firebaseAuth = FirebaseAuth.getInstance();
    firebaseAuth.createUserWithEmailAndPassword(user.getEmail().toString(), user.getPassword().toString())
            .addOnSuccessListener(success).addOnFailureListener(failure);
}

and invoke it

saveData(user, new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult authResult) {
                    // TODO handle result
                }
            }, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            String message = "Fail" + e.getMessage();
        }
    }); 

Something like that.

ConstOrVar
  • 2,025
  • 1
  • 11
  • 14
  • this solution is very good but, when i used to this solution with MVP Pattern , i send two object (OnSuccessListener success, OnFailureListener failure) in presenter constructor that make view careless.can you send example of user firebase with MVP Pattern thanks – user9213317 Oct 10 '18 at 00:04
  • @user9213317 if we speak about MVP and you want that code to be placed in `Presenter`, you shouldn't pass that callbacks in constructor - simply you can trigger `View` directly inside that callbakcs (implemented by `presenter`) – ConstOrVar Oct 10 '18 at 06:44