rufo
rufo

Reputation: 5537

State Persistent Activity Android

I have an application with a parent activity that allows to select a catalog, and a "child" activity that shows the data for the selected catalog.

I start my "child" activity with (this is Xamarin, but I do not think it makes a difference):

var catalog = new Intent (this, typeof(CatalogActivity));
catalog.PutExtra ("CatalogId", cat.Id);
StartActivity (catalog);

I would like the child activity to remember the state. So if the user goes into the child, return to the parent, and goes back into the child, the second time things are as the user left it the first time (please note that if the user closes the app the state will be lost, and that is fine - I am not trying to deal with that).

I am new to Android, not sure what the proper way to handle this scenario is. I could save the state manually, but what I would really expect is a way to tell Android to not kill the activity object and to let me invoke it in the future.

Please advise. Thanks.

Upvotes: 1

Views: 1078

Answers (1)

Rich
Rich

Reputation: 36806

If you want state to be persisted outside of the navigation flow, then don't pass it to the activity with an intent. In this case, you can have a singleton or static class that represents the state, set the state when a selection is made, and then read the state when your child activity loads. The quick and dirty way would be to set a static variable on the CatalogActivity with the current catalog id...that will outlast the life cycle of a single instance of your activity. Or, as you've alluded to in the question, you can easily read and write this value to SharedPreferences if you want to persist even after the app shuts down.

Upvotes: 1

Related Questions