Search code examples
javaandroidauthenticationfirebase-authenticationsharedpreferences

How to prevent users from being asked to re-login when closing the app using SharedPreferences and Firebase Authentication


I'm still learning about Firebase. I created a login program using Firebase authentication. When making the LoginActivity and HomeActivity programs run smoothly, when I press the back button and then open the application again, the user is asked to re-login. How can I make the user not be asked to re-login?

I've tried to find a solution to the same question on stackoverflow and several channels on YouTube, but haven't found an answer. I would really appreciate any answer, and I'm sorry if my English is messy.

This is the code snippet from LoginActivity.

FirebaseAuth mAuth = FirebaseAuth.getInstance();

SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);

mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        progressBar.setVisibility(View.GONE);
                        if (task.isSuccessful()){
                            Toast.makeText(LoginActivity.this, "Login succes !", Toast.LENGTH_SHORT).show();
                            user = mAuth.getCurrentUser();
                            updateUI(user);
                        }else{
                            Toast.makeText(LoginActivity.this, "Login Gagal !", Toast.LENGTH_SHORT).show();
                        }
                    }
                });


private void updateUI(FirebaseUser user) {
        if (user != null){
            String id = user.getUid();
            String userEmail = user.getEmail();
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("firebaseKey", id);
            editor.commit();

            gotoHomeActivity();
        }
    }

private void gotoHomeActivity() {
        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

        finish();
    }

And this is the code snippet from HomeActivity.

FirebaseAuth mAuth = FirebaseAuth.getInstance();

 SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);


String uid = sharedPreferences.getString("firebaseKey", "");

Solution

  • Once your user has logged in, they generally don't need to log in again when using FirebaseAuth. The problem is probably that you are calling the "sign in" routine every time.

    Instead, you should first add an auth state listener on your login screen, and when you get a response there you can either go to the home screen (if they are already logged in) or initiate the sign-in process.

    mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() != null) {
                    // already logged in, go to home screen
                }
                else {
                    // initiate sign-in
                }
            }
        }
    );
    

    Be aware that the listener will be called as soon as you register a listener, and sometimes again shortly thereafter. If that ends up being a problem there are some solutions for it at the linked question.

    Kotlin Version

    auth.addAuthStateListener(AuthStateListener { firebaseAuth ->
        if( firebaseAuth.currentUser != null ) {
            // user is already logged in, go to home screen
        }
        else {
            // initiate sign in
        }
    })