0

I have been wondering for a while now in this question on stack overflow one solution for passing complex data in-between activities on Android is the usage of static data members.

But somehow I get the feeling that this is not the way how you should do it even thou it seems to be the easiest way.

Therefore my question what is the downside of using static members for passing complex data.

Community
  • 1
  • 1
Duncan
  • 82
  • 6

2 Answers2

1

Using static members should be avoided. It's one of the worst ways to pass data in Android. Static objects persist beyond the application's lifecycle. So a user can back out of your app and your data lives on because the class is still loaded in the JVM. That's very bad.

Sometimes, Otto can be a good option for passing complex data around and it plays nicely with the Activity Lifecycle. Another alternative I've seen on many projects is good old fashioned listeners or callbacks. There's also intent services and local broadcast managers.

There are a lot of ways to share complex data. I would consider "static" objects a non-starter. Avoid them like the plague.

gMale
  • 17,147
  • 17
  • 91
  • 116
1

A static reference to pass data between components could be used if all of these conditions are met:

  • It is only accessed via 1 process
  • The data it contains does not hold a reference to any specific component (Activity, Fragment, Service e.t.c) except for the Application (which is a static singleton anyway)
  • The data does not keep a reference to anything else that may not have the same life cycle as the data
  • The data is too complex, or large to reasonably Serialise, Parcel or otherwise pass via Bundles, and doing so would effect the performance of the application.
  • It is correctly synchronised if accessed from different threads
  • The data is correctly managed and released when no longer required, avoiding leaking the memory needed to store it

Since these are quite restrictive conditions, a different approach (some suggested by gmale) is usually better.

The biggest drawback in my opinion is the management of the static data - it is usually difficult to tell when the data is no longer needed and when it can be released.

FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37