How to close activity and go back to previous activity in android
I have a main activity, that when I click on a button, starts a new activity, i used the following code to do so:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
The above code was run from the main activity.
Now in my new activity which is called by the main activity, I have a back button. When I click on this back button I want my new activity to close and it must go back to the original main activity.
I have tried calling super.finish()
and just finish()
(from the new activity) but this then closes my entire application (including my main activity).
How can I just close the activity that is currently in focus, and then return to the main activity?
EDITED
The fact that my phone's back button also closes my entire app, leads me to think that i have started up the second activity incorrectly?
OK I have been looking,
I created a Settings Activity that uses the same manifest code and the same code to Start the activity.
For the settings Activity when I push the back button, it returns to the Main activity.
With the activity mentioned above in the main question it simply exits my entire app.
So the problem doesn't seem to be with the code to finish the activity but the activity itself.
Solution 1:
I think you are calling finish()
method in MainActivity
before starting SettingsActivity
.
The scenario which you have described will occur in following two ways:
EITHER
You have set android:noHistory = "true"
for MainActivity
inside AndroidManifest.xml
which causes MainActivity
to finish
automatically on pressing the back key.
OR
Before switching to your 'SettingsActivity', you have called finish()
in your MainActivity
, which kills it. When you press back button,since no other activity is preset in stack to pop, it goes back to main screen.
Solution 2:
You can go back to the previous activity by just calling finish() in the activity you are on. Note any code after the finish() call will be run - you can just do a return after calling finish() to fix this.
If you want to return results to activity one then when starting activity two you need:
startActivityForResults(myIntent, MY_REQUEST_CODE);
Inside your called activity you can then get the Intent from the onCreate() parameter or used
getIntent();
To set return a result to activity one then in activity two do
setResult(Activity.RESULT_OK, MyIntentToReturn);
If you have no intent to return then just say
setResult(Activity.RESULT_OK);
If the the activity has bad results you can use Activity.RESULT_CANCELED (this is used by default). Then in activity one you do
onActivityResult(int requestCode, int resultCode, Intent data) {
// Handle the logic for the requestCode, resultCode and data returned...
}
To finish activity two use the same methods with finish() as described above with your results already set.