Home > Enterprise >  Keeping the user logged in in Android Studio
Keeping the user logged in in Android Studio

Time:11-25

I am trying to make an app with login function and i want to keeping the user logged in. i'm using firebase auth and android studio.

This is what I tried:

auth.signInWithEmailAndPassword(txt_email, txt_password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){
                    Intent intent = new Intent(login.this, sendForm.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                        finish();
                    }
                else {
                    Toast.makeText(login.this, "cant sing in", Toast.LENGTH_SHORT).show();
                }
            }
        });

CodePudding user response:

First you need to check if the user exists when you log in to the app from second time. If the user exists you directly take him to the MainActivity else you'll take him to the LoginActivity.

So, your launchActivity should be something that is other then Login/Main activities. Typically, it would be a splash screen. So, let's say you're launch activity is SplashActivity. Now, in your SplashActivity.java onCreate() do this:

FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (Objects.nonNull(currentUser)) {
    // This means that user has already logged into the app once.
    // So you can redirect to MainActivity.java

    startActivity(new Intent(this, MainActivity.class));
} else {
    // This means no user logged into the app before.
    // So you can redirect to LoginActivity.java

    startActivity(new Intent(this, LoginActivity.class));
}

If you don't want to use a SplashScreen, you can check for the user existence in LoginActivity.java using FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); and redirect him to MainActivity if currentUser is nonNull.

CodePudding user response:

When onComplete() method of signInWithEmailAndPassword gets called then save a boolean variable is_loggedin as true in SharedPreference.

Whenever app launches then check in sharedpreference whether is_loggedin value is true or false.

For more details on how to manage sharedpreference. Visit this link https://www.geeksforgeeks.org/shared-preferences-in-android-with-examples/

  • Related