602

I want to do something simple on android app. How is it possible to go back to a previous activity.

What code do I need to go back to previous activity

Swati Garg
  • 995
  • 1
  • 10
  • 21
Troj
  • 11,781
  • 12
  • 40
  • 49
  • 5
    Keep track of the last open activiy – Vuk Oct 27 '10 at 23:41
  • 72
    You just simple call finish(); Cheers – Nguyen Minh Binh Apr 07 '11 at 08:33
  • super.finish(); if you are calling it from inside of the activity! – happyhardik Sep 10 '12 at 12:14
  • 5
    One question here: If android has destroyed the previous activity due to less memory or other issues, then that activity would no longer be there in the backstack and then what happens? – Sunny Aug 12 '14 at 01:26
  • @Sunny I assume that the garbage collector starts with the top-most activity in the stack. So if there is no previous activity, there will also no current activity. But I just assume that because that behaviour would make more sense than freeing memory in a stack without any particular order. Correct my comment, if someone knows it exactly. – Sedat Kilinc Nov 20 '17 at 17:40
  • see this [answer](https://stackoverflow.com/a/54001336/5259996) i think this will help you. – Muhammad Helmi Jan 02 '19 at 04:56

23 Answers23

548

Android activities are stored in the activity stack. Going back to a previous activity could mean two things.

  1. You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.

  2. Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application. Haven't used them much though. Have a look at the flags here: http://developer.android.com/reference/android/content/Intent.html

As mentioned in the comments, if the activity is opened with startActivity() then one can close it with finish(). If you wish to use the Up button you can catch that in onOptionsSelected(MenuItem item) method with checking the item ID against android.R.id.home unlike R.id.home as mentioned in the comments.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Abhinav
  • 38,516
  • 9
  • 41
  • 49
  • 257
    Or if you opened activity with startActivity(), you can close with finish() (don't need pass any parameter) – neworld Jul 23 '12 at 07:11
  • 3
    Can you clarify where and how you use the finish() so when the user presses the up button it takes them to previous activity – RicNjesh Jan 20 '14 at 13:29
  • 4
    @RicNjesh In your onOptionsItemSelected method if the menuitem clicked has the id R.id.home then call finish(). It will close the current activity and take you back to the activity that started it with startActivity() – Anders Ullnæss Sep 03 '14 at 18:31
  • I am having the user go by many activities one after the other through intents. Do I need to do anything in order to make sure the app doesn't crash with too many activities on the stack? Thanks! – Ruchir Baronia Dec 11 '15 at 14:18
  • 2
    are you sure that activity 1 won't die at some point before you even finish activity 2? – user924 Nov 10 '18 at 19:25
249

Try Activity#finish(). This is more or less what the back button does by default.

adamp
  • 28,862
  • 9
  • 81
  • 69
101

Just write on click finish(). It will take you to the previous Activity.

Swayam
  • 16,294
  • 14
  • 64
  • 102
Umer Rana
  • 1,027
  • 1
  • 7
  • 2
  • 1
    Although onBackPressed() works as well, I think this solution is better for thinking about exiting an activity you need just for a bit .. e.g. OCR scanner in my case. Thanks! – Gene Bo Apr 09 '15 at 22:31
  • This satisfies my need..Thank you. – Roon13 Sep 12 '15 at 08:45
70

Just this

super.onBackPressed();
AtanuCSE
  • 8,832
  • 14
  • 74
  • 112
  • 3
    This call just finishes the current activity, so it will show the last activity visible. However if, there is no previous activity or it gets destroyed meanwhile, the application may exit. – r1k0 Sep 14 '12 at 13:51
  • 30
    This is hackish. You are not supposed to call this directly. This is one of the lifecycle methods and should be called by the android system. – Dheeraj Bhaskar Jan 01 '14 at 10:39
42
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.

For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B

Dmitry Ryadnenko
  • 22,222
  • 4
  • 42
  • 56
  • This is what works on my end. Would love to find out what would cause finish() not to work. – Relm Aug 29 '16 at 13:29
23

Just call these method to finish current activity or to go back by onBackPressed

finish();

OR

onBackPressed();
Akshay Paliwal
  • 3,718
  • 2
  • 39
  • 43
  • I am having the user go by many activities one after the other through intents. Do I need to do anything in order to make sure the app doesn't crash with too many activities on the stack? Thanks! – Ruchir Baronia Dec 11 '15 at 14:17
22

Are you wanting to take control of the back button behavior? You can override the back button (to go to a specific activity) via one of two methods.

For Android 1.6 and below:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Or if you are only supporting Android 2.0 or greater:

@Override
public void onBackPressed() {
    // do something on back.
    return;
}

For more details: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

Bryan Denny
  • 27,363
  • 32
  • 109
  • 125
16

Try this is act as you have to press the back button

finish();
super.onBackPressed();
Muhammed Fasil
  • 7,909
  • 2
  • 19
  • 28
  • Why did prefix `onBackPressed()` but not `finish()` with `super.`? – birgersp Nov 16 '21 at 19:02
  • finish() - will end the current activity super.onBackPressed() - it is calling from parent class that is why super is used – Muhammed Fasil Nov 22 '21 at 17:48
  • You don't actually need both lines. You can use either first to finish the current activity, or the second - to call the code that is responsible in activity for processing "back button" press. Previous activity in the first place do not need a "finish()" call along with startActivity() to make it still "alive" when closing the current activity to go back to it – George May 16 '23 at 20:44
15

Add this in your onCLick() method, it will go back to your previous activity

finish();

or You can use this. It worked perfectly for me

 @Override
  public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();

      if ( id == android.R.id.home ) {
         finish();
         return true;
       }

  return super.onOptionsItemSelected(item);
  }
Darshuu
  • 501
  • 5
  • 9
14

if you want to go to just want to go to previous activity use

finish();

OR

onBackPressed();

if you want to go to second activity or below that use following:

intent = new Intent(MyFourthActivity.this , MySecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Bundle is optional
Bundle bundle = new Bundle();
bundle.putString("MyValue1", val1);
intent.putExtras(bundle);
//end Bundle
startActivity(intent);
Ram G.
  • 3,045
  • 2
  • 25
  • 31
  • 1
    I found that finish() and onBackPressed() both work, but, in my app at least, finish() is very slow and onBackPressed() is much faster. Curious. – scrayne Nov 07 '15 at 00:10
  • I am having the user go by many activities one after the other through intents. Do I need to do anything in order to make sure the app doesn't crash with too many activities on the stack? Thanks! – Ruchir Baronia Dec 11 '15 at 14:18
12

If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :

NavUtils.navigateUpFromSameTask(this);

Where this is your child activity.

Thomas Decaux
  • 21,738
  • 2
  • 113
  • 124
10

Got the same problem and

finish();  OR super.onBackPressed();

worked fine for me, both worked same, but no luck with return

NoNaMe
  • 6,020
  • 30
  • 82
  • 110
8

You can explicitly call onBackPressed is the easiest way
Refer Go back to previous activity for details

Labeeb Panampullan
  • 34,521
  • 28
  • 94
  • 112
6

Start the second activity using intent (either use startActivity or startActivityForResult according to your requirements). Now when user press back button, the current activity on top will be closed and the previous will be shown.

Now Lets say you have two activities, one for selecting some settings for the user, like language, country etc, and after selecting it, the user clicks on Next button to go to the login form (for example) . Now if the login is unsuccessful, then the user will be on the login activity, what if login is successful ?

If login is successful, then you have to start another activity. It means a third activity will be started, and still there are two activities running. In this case, it will be good to use startActivityForResult. When login is successful, send OK data back to first activity and close login activity. Now when the data is received, then start the third activity and close the first activity by using finish.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Altaf Hussain
  • 5,166
  • 4
  • 30
  • 47
  • I am having the user go by many activities one after the other through intents. Do I need to do anything in order to make sure the app doesn't crash with too many activities on the stack? Thanks! – Ruchir Baronia Dec 11 '15 at 14:18
5

You can try this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
nikki
  • 3,248
  • 3
  • 24
  • 29
5

All new activities/intents by default have back/previous behavior, unless you have coded a finish() on the calling activity.

ameyx
  • 403
  • 5
  • 9
5
@Override
public void onBackPressed() {
    super.onBackPressed();
}

and if you want on button click go back then simply put

bbsubmit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});
Ziem
  • 6,579
  • 8
  • 53
  • 86
Md Hussain
  • 411
  • 4
  • 10
3

I suggest the NavUtils.navigateUpFromSameTask(), it's easy and very simple, you can learn it from the google developer.Wish I could help you!

wuxue
  • 113
  • 1
  • 13
3
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
      int id = item.getItemId();

      if ( id == android.R.id.home ) {
          finish();
          return true;
      }

      return super.onOptionsItemSelected(item);
 }

Try this it works both on toolbar back button as hardware back button.

Puni
  • 1,214
  • 2
  • 18
  • 34
3

There are few cases to go back to your previous activity:

Case 1: if you want take result back to your previous activity then ActivityA.java

 Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
               startActivityForResult(intent,2);

FBHelperActivity.java

 Intent returnIntent = new Intent();
 setResult(RESULT_OK, returnIntent);
 finish();

Case 2: ActivityA --> FBHelperActivity---->ActivityA

ActivityA.java

 Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
               startActivity(intent);

FBHelperActivity.java

after getting of result call finish();
 By this way your second activity will finish and because 
 you did not call finish() in your first activity then
 automatic first activity is in back ground, will visible.
0

Just try this in, first activity

Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);

In your second activity

@Override
public void onBackPressed() {
    this.finish();
}
byteC0de
  • 5,153
  • 5
  • 33
  • 66
0

First, thing you need to keep in mind that, if you want to go back to a previous activity. Then don't call finish() method when goes to another activity using Intent.

After that you have two way to back from current activity to previous activity:

Simply call:

finish()

OR

super.onBackPressed();
Monir Zzaman
  • 459
  • 4
  • 7
  • 2
    There is no point in overriding parent class's method if you are are just calling the overridden method and not customizing the behavior. – M. Gasimov Sep 25 '21 at 10:28
0

To go back from one activity to another by clicking back button use the code given below use current activity name and then the target activity.

@Override
public void onBackPressed() {
    // do something on back.
    startActivity(new Intent(secondActivity.this, MainActivity.class));
    return;
}
Akash Jaiswal
  • 31
  • 1
  • 2