Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restoring state in Android when using the 'up' button

I am using onSaveInstanceState() to store an ArrayList member variable and restore it in the onCreate() method of the main activity. This works in most circumstances such as rotating the screen etc. but if I open a new activity and use the 'up' button (not the back button) to navigate back to the main screen it seems to create a new main activity without passing the state bundle in onCreate().

I have confirmed that when the up button is pressed the onDestroy() method is called for the original instance of the main activity which makes no sense to me because I want it to resume the existing activity as if I had pressed the back button rather than create a new one.

Is there a way I can force the new activity to restore the old one or just resume the existing activity?

like image 447
archangel Avatar asked May 03 '13 08:05

archangel


People also ask

How do you restore the state of an Android activity?

State can be restored in either the onCreate() or the onRestoreInstanceState() methods of the activity by extracting values from the Bundle object and updating the activity based on the stored values.

How can you save the state of activity?

When the activity goes into the background, the system calls onSaveInstanceState() . You should save the search query in the onSaveInstanceState() bundle. This small amount of data is easy to save. It's also all the information you need to get the activity back into its current state.

How do I use onSaveInstanceState and onRestoreInstanceState on Android?

The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.

What is the use of savedInstanceState in Android?

The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.


1 Answers

Try setting the main activity's launch mode to singleTop, in your manifest:

<activity android:name="activityName" android:launchMode="singleTop" ... />
like image 118
FunkTheMonk Avatar answered Sep 30 '22 00:09

FunkTheMonk