I was developing a e-com application for my final year project. I am facing a problem like ex. "There is a user XXX if he logs into my app he should be logged inside my app every time he opens until he signs out". This is my problem and i have been stuck in this case for a long duration now please help me over come this one.
This is my code
mAuth.signInWithEmailAndPassword(usernamestring,pass).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
FirebaseUser user = mAuth.getCurrentUser();
Intent i=new Intent(Login.this,MainScreen.class);
mAuth.updateCurrentUser(user);
startActivity(i);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Login.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
CodePudding user response:
Firebase automatically persists the user information in local storage, and (also automatically) restores it when the app starts.
You should be seeing the signed in user when you check FirebaseAuth.getInstance().currentUser
, but if somehow that doesn't immediately work for you, consider implementing an auth state listener.
CodePudding user response:
Your code implementation is fine, what you have to do is redirect the user to your main screen after checking if user is already signed in at application startup. Something like
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
// Route to login page
} else {
// Route to home page
}
}
and for your logout function:
public void signOut{
FirebaseAuth.getInstance().signOut();
//Route to login page
}
Or
Instead of checking mAuth.getCurrentUser()
you could use sharedpreferences to save something like loggedIn:true
when user logs in and on startup check if true and redirect to home page and on logout make this loggedIn:false