25

Suppose you want to start a new activity and pass it some data from the current activity. If the data is of a primitive type you could simply use an intent and add extras, but how would you do this for more complex data structures like arraylists or objects?

aspartame
  • 4,622
  • 7
  • 36
  • 39

2 Answers2

60

You have a few options:

  1. You could wrap the more complex structure in a class that implements the Parcelable interface, which can be stored in an extra
  2. You could wrap the more complex structure in a class that implements the Serializable interface, which can be stored in an extra
  3. You use static data members to pass stuff around, since they are all in the same process
  4. You use external storage (file, database, SharedPreferences)
  5. As the person who just posted noted, use a common component, such as a custom Application or a local Service

What you do not want to do is pass big stuff via extras. For example, if you are creating an application that grabs pictures off the camera, you do not want to pass those in extras -- use a static data member (icky as that sounds). Intents are designed to work cross-process, which means there is some amount of data copying that goes on, which you want to avoid when it is not necessary for big stuff.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • A bunch of options as I suspected. Thanks! For this particular project I chose to go with option number 3. It ain't pretty but it does the job! – aspartame Sep 18 '09 at 00:16
  • I'm a big fan of Parcelables... they're easy to build and easy to pass. – Jeremy Logan Sep 18 '09 at 04:52
  • 5
    I hate them. They're a maintenance nightmare and very error prone. The only advantage over simply passing your object as a Serializable is the better performance. – mxk Sep 18 '09 at 07:37
  • http://stackoverflow.com/questions/2906925/android-how-do-i-pass-an-object-from-one-activity-to-another - for option 1 & 2. – Zolomon Nov 16 '11 at 13:27
  • 1
    http://parcelabler.com/ is very handy when trying to use Parcelables , hope it helps someone :) – vin Apr 28 '14 at 13:04
2

One option I am aware of is storing the data you are using in an Application object which all your activities can retrieve from context.

I have also heard of using Google Protocol Buffer to achieve a higher performing solution

j pimmel
  • 11,617
  • 6
  • 33
  • 43
  • I've read some posts arguing against Appication Object, such as http://www.developerphil.com/dont-store-data-in-the-application-object/ – Muhammad Mar 15 '15 at 15:01