Peter
Peter

Reputation: 1749

Return to previous Activity without deleting current state - Android

I wrote an Android app with several Activities and a Main Activity. When I go from the Main Activity to lets say Activity B, I want to "pause" the Main Activity, when the back button is pressed it should go back and reactivate the Main Activity instead of calling onCreate().

This shall work with all Activities, so if I click on a button to start Activity B, it shall also reactivate the old Activity B instead of creating a new state with onCreate().

How can I realize this?

PS: I already tried it with parcelable, but this do only work, if I close the application or something unexpected happens.

Upvotes: 1

Views: 624

Answers (3)

Igal
Igal

Reputation: 6083

Activities live in stack order. Each activity has its life cycle. When you close an activity (Activity B in your example) it eventually reaches onDestroy() method and removed from the stack order. It is by default in Android and there's nothing you can do about it.

What you can do is rewrite the onStop() method in Activity B and save some activity data (like text in EditText, for example) in SharedPreferences - read here. Then in your onCreate() method you can call for SharedPreferences, check if it's not empty and restore the text in the EditText by pulling appropriate value by key.

Upvotes: 1

srs
srs

Reputation: 647

It is by default in Android. If you Start Activity B from Activity A then activity A goes in stopped state. Below methods will be called of Activity A

  1. onPause()
  2. onStop()

When you tap on Back key on Activity B. Below methods of Activity A will be called.

  1. onRestart()
  2. onStart()
  3. onResume()

For reactivating Activity B, you can set Activity B launch mode as singleInstance. This will make sure that only single instance of Activity B will be created. onCreate will be not be called again. onNewIntent will be called when that activity is reactivated.

Refer: http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

Upvotes: 2

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10288

It's always possible that the first activity may be destroyed when you start another activity. It will be recreated when you go back to it. Every app should be written with this possibility in mind. To make sure your activities can handle being destroyed and recreated, turn on the "don't keep activities" developer option.

Upvotes: 2

Related Questions