0

I have a question similary to this guy, but slightly different. In the original question, he says

Suppose you want to start a new activity and pass it some data from the current activity.

The first answer talks about putting things in Extras, so presumably he's talking about passing Intents.

However, what if you only wanted to pass between two instances of the same activity? For example, if you rotate the screen, the "old" instance of an activity is destroyed and a "new" one created. The way to pass information between these is through a Bundle. I know how to pass primitive data types with onSaveInstanceState.putXXX and .getXXX. But what if I have an array of Objects? How can I pass these in a Bundle? Are Parcelable and Serializeable my only options?*

*assuming I don't want to use a static variable

Community
  • 1
  • 1
tir38
  • 9,810
  • 10
  • 64
  • 107
  • *"Are `Parcelable` and `Serializeable` my only options?"* - In short: yes. However, since `Parcelable` outperforms `Serializable` (it was created specifically for high-performance IPC), it's worth going the extra mile in terms of implementation overhead, especially if you're planning on passing around data **sets**. – MH. Aug 18 '13 at 21:46

1 Answers1

1

Basically we have a couple of options here.

Option 1 is to use Activity.onSaveInstanceState() method. There you store everything into an instance of Bundle class. Bundle requires simple, parcelable or serializable types. You can pass arrays too, but these must be arrays of those types.

Option 2 would be to override Activity.onRetainCustomNonConfigurationInstance() and return your array from there. New instance of this activity can retrieve this array by calling Activity.getLastNonConfigurationInstance(). Although this option works fine, it is already deprecated. This is where 3rd option comes into play.

Option 3 is to use a retained Fragment. Here the idea is to create a Fragment and to call Fragment.setRetaineInstance(true) in either onCreate() or onCreateView() of this fragment. Once called, this fragment becomes "retained". If you rotate your device, then new activity instances will be created with every new rotation, but the same instance of retained fragment will be passed to every new instance of the activity. If you keep your array there, it will be available in every new activity instance instantly. This would be a way to go.

I would like to note, that option 1 is persisted. If your app goes into background and Android kills it and later starts again, you will have your array delivered to onCreate(Bundle savedInstanceState). In contrast to this, options 2 and 3 will lose the state. If you can re-create your array every time activity is created, you can go with option 2 or 3.

sergej shafarenka
  • 20,071
  • 7
  • 67
  • 86
  • Option 1 ended up being the best. I needed the persistent. I realized that as long as my object ```implements Serialiable``` I would be fine – tir38 Nov 05 '13 at 03:31