To check if a user is logged in:
private FirebaseAuth firebaseAuth; FirebaseAuth.AuthStateListener mAuthListener;
Then in your onCreate:
firebaseAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener(){ @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){ FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user!=null){ Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } } };
This can be created in the authorization state class or in the interface. Then you can simply call the authentication state or enable any activity with which you want to do this:
Checking the authorization status when performing an action:
@Override protected void onStart() { super.onStart(); firebaseAuth.addAuthStateListener(mAuthListener); } @Override protected void onResume() { super.onResume(); firebaseAuth.addAuthStateListener(mAuthListener); } @Override protected void onStop() { super.onStop(); firebaseAuth.removeAuthStateListener(mAuthListener); }
Now about your login: after setting your logical values ββfor verification, the user has entered the state: (by default, the logical value is set to false)
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressBar.setVisibility(View.GONE); if (!task.isSuccessful()) {
and, if the user has successfully logged in, set it to true, and then the intention:
else { String userid = firebaseAuth.getCurrentUser().getUid(); DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference("Users").child(userid); current_user_db.setValue(true); Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); }
After that, your node will be set to False if the user is logged in, or false if the user is not logged in.