2

I programmatically create a RelativeLayout with some other views inside it and add it to the parent which is defined in XML. But all the views (incl. the layout) that were created programmatically disappear after the activity is re-created. Do I need a SharedPreferences object to save the values and then re-create the layout or is there an easier way to save it?

P.S. all new created views get an id assigned

Droidman
  • 11,485
  • 17
  • 93
  • 141
  • are they created in onCreate, onResume, ? – CodeShane Dec 25 '12 at 20:47
  • they are created in onResume() as a result of a button click – Droidman Dec 25 '12 at 21:15
  • "Do I need a SharedPreferences object to save the values" - Yes, of course - or some other means of persistent storage. Everything your program produces will easily be lost if it's not *explicitly* persisted. (Except for the [preference](http://developer.android.com/reference/android/preference/package-summary.html) API, which includes code to transparently persist settings.) – JimmyB Dec 25 '12 at 21:19

2 Answers2

3

I recommend you look into Activity.onSaveInstanceState(Bundle):

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState()). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation [ via super.onSaveInstanceState() and super.onRestoreInstanceState()], otherwise be prepared to save all of the state of each view yourself.

https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

as well as my answer here:

How can I assign an ID to a view programmatically?

Community
  • 1
  • 1
CodeShane
  • 6,480
  • 1
  • 18
  • 24
3

Do I need a SharedPreferences object to save the values and then re-create the layout

You say that you are creating these widgets in onResume(). Your code in onResume() needs to know what widgets need to be created. If this is purely transient information, and you are worried about things like the activity being destroyed and re-created due to a screen rotation or other configuration change, use onSaveInstanceState() on the activity or fragment to pass data about these widgets from the old to the new instance of the activity. If, on the other hand, you are worried about being able to re-create these views several months later, you need to store this information persistently: SharedPreferences, database, some other file structure, "the cloud", etc.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491