0

Why do we send data from one activity to another with intent? Can't we use static variable instead and access from other activity using ClassName.TheVariable ?

Mr.India
  • 674
  • 2
  • 9
  • 19

3 Answers3

3

This is some kind of good OOP patern when data encapsulated in one instance. You can read about Why are static variables considered evil?.

And also look at another good android pattern Content Providers or Using Shared Preferences.

And If you will use some of this common patern another developers will say "Thank you" in future.

Community
  • 1
  • 1
Borys
  • 1,793
  • 2
  • 17
  • 32
1

If Android kills and restarts the process for your application, then the static variables will get assigned to their default values. You might be better of using SharedPreferences or intent instead of static variables if you want values to persist.

Using static variables is not recommended. Static variables are stored in a PermGen section of the heap. Even if the class finishes it works the static variables stays in the heap. The garbage collector does mark and sweep. If you have a static variables in the 1st activity which is referenced in the 2nd activity, the reference stays long.

You might get memory leaks if your using more static variables. Also reduce use of unnecessary objects.

Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
0

Yes you can have static data like you suggest. Note that a good way of having static data across an application can be to have an application object, see Android documentaion about application object.

Stochastically
  • 7,616
  • 5
  • 30
  • 58
  • Yes, but it is bad practice and design. – Simon Jun 08 '13 at 11:01
  • @Simon I agree that it can be bad design, but equally I think there are a lot of situations where it's good design. For example, how about the default language for an application? For me, that needs to be a global state variable. – Stochastically Jun 08 '13 at 11:06
  • @Stochastically, if you need to know this store it in SharedPreference and get data when you need. – Borys Jul 22 '13 at 07:08
  • @Borys I was just giving an example of something that's appropriate for storage as static data. My comment isn't specifically related to Android, it's a general programming comment. – Stochastically Jul 22 '13 at 12:34