ChatGPT解决这个技术问题 Extra ChatGPT

Android: Go back to previous activity

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

Keep track of the last open activiy
You just simple call finish(); Cheers
super.finish(); if you are calling it from inside of the activity!
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 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.

p
phoenix

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

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. 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.


Or if you opened activity with startActivity(), you can close with finish() (don't need pass any parameter)
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 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()
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!
are you sure that activity 1 won't die at some point before you even finish activity 2?
a
adamp

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


why #? or it's a dot?
I believe he meant this.finish();
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.
@Tanis.7x Is there and indicator for static methods?
@Benten that would be ., ie: Activity.someStaticMethod()
S
Swayam

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


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!
This satisfies my need..Thank you.
A
AtanuCSE

Just this

super.onBackPressed();

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.
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.
D
Dmitry Ryadnenko
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


This is what works on my end. Would love to find out what would cause finish() not to work.
B
Bryan Denny

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


A
Akshay Paliwal

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

finish();

OR

onBackPressed();

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!
D
Darshuu

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);
  }

M
Muhammed Fasil

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

finish();
super.onBackPressed();

Why did prefix onBackPressed() but not finish() with super.?
finish() - will end the current activity super.onBackPressed() - it is calling from parent class that is why super is used
R
Ram G.

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);

I found that finish() and onBackPressed() both work, but, in my app at least, finish() is very slow and onBackPressed() is much faster. Curious.
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!
T
Thomas Decaux

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

NavUtils.navigateUpFromSameTask(this);

Where this is your child activity.


N
NoNaMe

Got the same problem and

finish();  OR super.onBackPressed();

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


L
Labeeb Panampullan

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


A
Alexander Farber

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.


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!
n
nikki

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);
}

a
ameyx

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


Z
Ziem
@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();
    }
});

w
wuxue

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


P
Puni
 @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.


G
Gyan Swaroop Awasthi

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.

D
Daniel Nyamasyo

Besides all the mentioned answers, their is still an alternative way of doing this, lets say you have two classes , class A and class B.

Class A you have made some activities like checkbox select, printed out some data and intent to class B. Class B, you would like to pass multiple values to class A and maintain the previous state of class A, you can use, try this alternative method or download source code to demonstrate this

http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/

or

http://developer.android.com/reference/android/content/Intent.html


b
byteC0de

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();
}

keeps crashing, data does not persist I think
M
Monir Zzaman

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();

There is no point in overriding parent class's method if you are are just calling the overridden method and not customizing the behavior.
A
Akash Jaiswal

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;
}