Search code examples
androidandroid-activityactivity-finish

Android Studio finish() activity not working the first time


I am working on this Android Studio project, and after I'm making some checks in the Login activity, I want to be redirected to the MainActivity and finish the Login activity. However, after I login and I am being redirected to the MainActivity, if I press the back button, it will redirect me back to the Login Activity(the first time the login activity not being closed/finished). If I try to repeat the process and press back, this time works as desired, that is, it closes the app(the Login activity is closed/finished) I checked my code a few times now, and I am not starting the same activity twice, so does anybody know why this happens and how to fix it?


Solution

  • Try to use finishAffinity() which closes the current activity and clears the stack. Then you will be left with MainActivity only.

    More information: https://developer.android.com/reference/android/app/Activity#finishAffinity()