Home » Android » android – public static variable or use putExtra method of intent class

android – public static variable or use putExtra method of intent class

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a general question here about performance, and which of which should I do and which I should not use.
I am actually using in my App two activities, let us call “theFirst” and “theSecond” activity.

In theFirst activity I have a public static object, in my case, its a list of a custom object made by me, called Conjunction.

When I call the theSecond activity I want to get the content of this list.
So should I use the public static variable ? is there any problem? There will be only one instance of theFirst activity right? So no problem using public static variable..? I guess.

Or should I compute the entire list and put the information on a big String and send it to theSecond activity using the putExtra method?

A good explanation on this would be very good and I would really appreciate it :)

How to&Answers:

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 link stays long. You might get memory leaks if your using more static variables. Also reduce use of unnecessary objects.

Static variables are referenced by Class objects which are referenced by ClassLoaders -so unless either the ClassLoader drops the Class somehow or the ClassLoader itself becomes eligible for garbage collection the static variables won’t be garbage collected. So if you are using static variables referenced in many class those classes and the one in which static variables are declared cannot be garbage collected unless those classes are available for garbage collection. So this leads to heap memory expanding leading to memory leaks.

I recommend using puExtra for primitives types. In your case using singleton should help.

In this video the guy talks about why static variables should not be used and how to avoid memory leaks.http://www.youtube.com/watch?v=_CruQY55HOk. The guy talks about using MAT Analyzer to check for memory leaks.

Also have a look at this link. http://developer.android.com/guide/faq/framework.html.Have a look at the details under the heading *How do I pass data between Activities/Services within a single application?.

Answer:

public static is not a good idea. “theFirst” Activity may be terminated by the system in some cases. Get through: Activity Lifecycle may help you how activity works.

Better use putExtra not really as a string but also look at putExtra for Parselable or Serializable object. see here for serializable