Reputation: 23
I have a log in activity which calls a method 'Log in' from another Java class. In the Log in activity, when the log in button is pressed it calls the method 'Log in' from another class which should return true if all the log in details are correct which allows the user to proceed.
I have already tried declaring a global variable as final however this variable cannot be manipulated.
Code:
public boolean LogIn(String email, String password) {
boolean success = false;
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
success = true; // Error here
} else {
success = false; // Error here
}
}
});
return success;
}
Upvotes: 0
Views: 192
Reputation: 55
You can use AtomicBoolean as final here to use in an inner class, but as the function is asynchronous, LogIn return value is not set correctly and you must change how you handle your login request.
Upvotes: 0
Reputation: 148
The error is you cant change the state of a local variable in anonymous inner class in java if you are using local variable in side a anonymous inner class those local variable will be considered as final. In your case boolean success is local variable in logIn method it is considered as final variable you cannot re assign it in the anonymous inner class.
In your case think it will helps
public boolean LogIn(String email, String password) { StringBuffer buffer = new StringBuffer("") : firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { buffer. append("true") ; } else { buffer. append("false") ; } } }); return buffer. toString(). equals("true") ; }
Upvotes: 0
Reputation: 317392
signInWithEmailAndPassword
is asynchronous and returns immediately with a Task object the tracks the ongoing work. This means that LogIn
also returns immediately with the initial value of success
. Some time later, your completion listener on the Task will get invoked, whenever the data is ready. That's where you should deal with the results of the sign in.
You're trying to turn an asynchronous method into a synchronous method. This isn't a good idea. Use the listener to handle the results. You can't pass a value out of that listener.
Upvotes: 1