3

Another design question for you If I have 5 activities that can result from one activity A->B A->C A->E .... Etc

And activity A has values that need to be passed to all other activites, then do you recommned passing them through intent or should I just have a global static variables in activity A and read the values in any other activity?

Thank you

Snake
  • 14,228
  • 27
  • 117
  • 250

2 Answers2

5

Definitely don't use static public variables.

You should use:

  • SharedPreferences or DB for data that should be persisted (cached)
  • Intent extras if data is needed in some part of app (couple of activities)
  • Application inheritor for application-wide data, that shouldn't be persisted.
kzotin
  • 5,365
  • 3
  • 29
  • 36
  • 1
    Great answer but not sure why not static variables. Whats the down side? – Snake Mar 03 '12 at 23:56
  • 1
    It brings you back to stone age of procedural programming, and will cause a mess in any big project. – kzotin Mar 04 '12 at 10:45
  • 2
    Yeah, but if you're one person doing a quick little project, it might save you time and effort without creating spaghetti code. Creating extra work and lines of code purely to avoid "procedural programming" isn't worth it all the time. – CorayThan Feb 14 '14 at 09:15
2

You can subclass android.app.application and use that class to share data between activities.

public class MyApp extends Application {
  String mySharedString = "Hello World";
}

See How to declare global variables in Android?

Community
  • 1
  • 1
Nick
  • 748
  • 1
  • 5
  • 23