Android: Go back to previous activity
Asked Answered
S

23

606

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

Seaver answered 27/10, 2010 at 23:13 Comment(6)
Keep track of the last open activiyTownsley
You just simple call finish(); CheersUnhand
super.finish(); if you are calling it from inside of the activity!Kob
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?Peyton
@Peyton 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.React
see this answer i think this will help you.Superfluous
O
550

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.

Occlude answered 27/10, 2010 at 23:49 Comment(5)
Or if you opened activity with startActivity(), you can close with finish() (don't need pass any parameter)Frostbitten
Can you clarify where and how you use the finish() so when the user presses the up button it takes them to previous activityHeavily
@Heavily 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()Kelcey
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!Amplitude
are you sure that activity 1 won't die at some point before you even finish activity 2?Peltast
S
250

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

Sirajuddaula answered 27/10, 2010 at 23:47 Comment(7)
why #? or it's a dot?Loudmouthed
I believe he meant this.finish();Criterion
The # is an indicator that finish() is a non-static method of the Activity class. It's not valid Java, but it helps explain how one might use the method.Lavernalaverne
@Tanis.7x Is there and indicator for static methods?Clipboard
@Clipboard that would be ., ie: Activity.someStaticMethod()Lyingin
If you just have the context, you can also do like that : ((BaseActivity) context).finish()Basophil
The OP probably miscopied from the link (Activity.html#finish()), LOL.Motherly
P
103

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

Pathogenesis answered 21/9, 2011 at 8:50 Comment(2)
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!Orientation
This satisfies my need..Thank you.Convolvulaceous
S
70

Just this

super.onBackPressed();
Sydel answered 18/1, 2012 at 6:55 Comment(2)
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.Weird
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.Henrie
R
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

Recycle answered 10/4, 2012 at 8:14 Comment(1)
This is what works on my end. Would love to find out what would cause finish() not to work.Overhear
R
24

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

finish();

OR

onBackPressed();
Redman answered 4/2, 2015 at 9:32 Comment(1)
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!Amplitude
F
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

Fled answered 27/10, 2010 at 23:41 Comment(0)
M
16

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

finish();
super.onBackPressed();
Meshuga answered 8/8, 2016 at 9:29 Comment(3)
Why did prefix onBackPressed() but not finish() with super.?Hundredth
finish() - will end the current activity super.onBackPressed() - it is calling from parent class that is why super is usedMeshuga
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 itDeviationism
H
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);
  }
Haustellum answered 20/9, 2017 at 12:41 Comment(0)
B
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);
Bedevil answered 30/6, 2015 at 21:27 Comment(2)
I found that finish() and onBackPressed() both work, but, in my app at least, finish() is very slow and onBackPressed() is much faster. Curious.Weddle
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!Amplitude
J
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.

Julesjuley answered 27/11, 2013 at 12:23 Comment(0)
G
10

Got the same problem and

finish();  OR super.onBackPressed();

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

Geosynclinal answered 30/1, 2018 at 4:24 Comment(0)
T
8

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

Trinity answered 13/4, 2011 at 15:16 Comment(0)
V
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.

Vandiver answered 18/7, 2013 at 8:50 Comment(1)
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!Amplitude
Z
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);
}
Zephyr answered 31/8, 2012 at 10:16 Comment(0)
D
5

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

Dahlgren answered 7/4, 2013 at 17:38 Comment(0)
M
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();
    }
});
Martie answered 2/2, 2015 at 4:42 Comment(0)
N
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!

Normalize answered 10/10, 2015 at 14:26 Comment(0)
E
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.

Egger answered 30/7, 2017 at 14:23 Comment(0)
C
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.
Cottingham answered 30/7, 2018 at 13:45 Comment(0)
D
1

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();
Domesticity answered 29/8, 2019 at 11:13 Comment(1)
There is no point in overriding parent class's method if you are are just calling the overridden method and not customizing the behavior.Wakashan
S
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();
}
Seraphine answered 30/8, 2017 at 9:20 Comment(1)
keeps crashing, data does not persist I thinkCatchfly
I
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;
}
Interrupter answered 17/3, 2022 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.