abu abu - 2 months ago 9
Android Question

Check if user has signed in using Password Authentication in Firebase

I am using password authentication of

firebase
. I have registered my app with
firebase
and enabled the email/password authentication.In my
MainActivity
,i have signup and login button which opens signup and login activity.If there is a successfully signup/login, i am redirecting the user to
ImageActivity
. Up to this it works fine.When the user is in
ImageActivity
and if he/she press back button,the app should close but instead i am taken to the Login/Signup Activity. I have already written the following code in
onCreate
of both Login/Signup Activity.

auth = FirebaseAuth.getInstance();

if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, ImageActivity.class));
finish();
}


I have wrote this code in my
MainActivity
onCreate
also.
Please help

Answer Source

To prevent this problem you can do couple of things

First: When you start ImageActivity you clear the back stack and you should declare that Image Activity as a new Task. To do that you should write following code in LoginActivity or SignupActivity

auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
         Intent intent = new Intent(LoginActivity.this, ImageActivity.class); // Change LoginActivity to SignupActivity if you are calling ImageActivity from SignupActivity
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
         startActivity(intent);
         finish();
    }

If you start Signup/LoginActivity from MainActivity, make sure that you do the same when you start LoginActivity and SignupActivity from MainActivity.

After doing that implement onBackPressed on your ImageActivity class. And call finish() in onBackPressed. The code is below

@Override
public void onBackPressed() {
    finish();
}

After doing this I hope that your problem will be solved.