Reputation: 5517
when I declare and initialize a variable as static in my main activity and the activity gets destroyed. Can I still access the content of the variable?
For example to always access a AsyncTask which I store to this variable? What I want is to be able to access to it also after an orientation change.
Upvotes: 46
Views: 30316
Reputation: 49
I recently built a background music for a quiz app and I could control it from any activity because it was in a static class. catch was that the music kept restarting so I had to store the time stamp on onPause and pass to next activity to continue . static class might be destroyed but why not store it's value in sharedPreference before the state changes. like on onDestroy() so you initialize it from anywhere. For the question: 1 save the value in savedInstance state 2 save the values in sharedPreference on onPause or onDestroy of the oncreate state.
Upvotes: -1
Reputation: 763
Static variables are created once the enclosing class is loaded into the memory. You may initialize the static variables at the load time in a static block or while the code is already running like in your case. Static variables are related to the type rather than single instance of the type because of that once a static variable is created, it lives as long as the process which contains it(in android, it means that it lives along with the application). The problems it may cause are:
For your case:
ViewModel architecture component persists objects across the configuration changes. You can use it however you still need to be careful about context leaks. Another option is to use a fragment without a UI. You call function setRetainInstance(true)
in the fragment and the system persists this fragment across configuration changes. This fragment keeps your data and you can get this fragment via fragment manager after a configuration change occurs. Actually the latter option is underlying mechanism of the ViewModel. For multithreaded cases like AsyncTask, the operation running in a separate thread should not keep reference to the context. You should run the task in a separate layer then update the necessary fields in the viewModel or retained fragment.
Upvotes: 4
Reputation: 1727
Static variables are tied to the class itself. As long as the class is in memory, the variable will be kept.
Classes rarely get garbage collected as they live in what is called the Permanent Generation
of memory space (you can find more about how generational GC works here https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html).
You can look at https://developer.android.com/topic/performance/memory-overview to get a better understanding of how memory is managed in Android, but unless your app is doing something very very unusual, the permanent generation is allocated all the memory it needs to hold all it's classes and will not be garbage collected.
Orientation changes will not clear a static variable, however if that's your goal using a static variable isn't very appropriate. You can keep instance state when orientation changes by using setRetainInstance
or similar (see Android: how do I prevent class variables being cleared on orientation change for an answer)
Upvotes: 8
Reputation: 2412
I'm actually surprised that nobody was able to find a reference. It's right there on Wikipedia:
...a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is stack allocated and deallocated on the call stack; and in contrast to objects, whose storage is dynamically allocated and deallocated in heap memory.
This definition is for general programming languages. But it can be used as a reference to Android
. However, in object-oriented programming languages:
In object-oriented programming, there is also the concept of a static member variable, which is a "class variable" of a statically defined class, i.e., a member variable of a given class which is shared across all instances (objects), and is accessible as a member variable of these objects. A class variable of a dynamically defined class, in languages where classes can be defined at run time, is allocated when the class is defined and is not static.
Meaning that in Android, where Java, is used static variables have a lifetime equal to the lifetime of the app, or the instance that is using it, if that static variable is not created at runtime.
Upvotes: 0
Reputation: 200
yes the value which you set in it remains persisted even after the activity closes but not after the application closes.
Upvotes: 0
Reputation: 1271
The value of static variables will persist as long as the class is loaded - it has almost nothing to do with Activity lifecycle (onCreate, ..., onDestroy)
The first time you access a class from code it will get loaded and then it won't go away until there is a reason to unload it.
Android will unload a class if your app gets completely removed from memory - either via a task-killer or when your app is no longer active and memory gets low.
So if you create an android application and initialize a static variable, it will remain in the JVM until one of the following happens: 1. the class is unloaded 2. the JVM shuts down 3. the process dies
Upvotes: 0
Reputation: 39
A static variable is associated with the lifecycle of class. Once an activity is destroyed than that static variable will also be cleaned up.
If you still want to access that variable you have 2 options:-
Upvotes: -1
Reputation: 1031
I believe I finally found you a reference -
The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more references to it. You can explicitly drop a reference by setting the variable holding the reference to null.
https://docs.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
To be clear, it is possible for static variables to remain initialized preventing the class to be properly garbage collected (aka a memory leak).
Upvotes: 0
Reputation: 1073
Once I have developed the application using lots of static vars, The problem with static vars is that once android has low memory it automatically removes the static variable and if your views are connected with static variable it won't show or worse application will crash. I recommend using shared preferences or other methods to store the variables.
problems
If your android memory is low the static variables will be removed from ram and you have to reinitialize them
If your view is attached to the static variables like ArrayList to recycler view it will throw errors like null pointer exceptions for that you have to check balance every time you initialize the view.
The main problem is of your variable is too big like ArrayList with images in it some time it can give out of memory exception
Upvotes: -2
Reputation: 3128
They stay even if you close the app with pressing back button as long as you don't clear them from the recent apps.Proof : well I've tested it you can too it's easy ;).
Upvotes: 1
Reputation: 361
Static variables or static blocks are not associated with object. These are class level variable not object associated. If we destroy object, static variable will not destroy which is defined in same class. Static variable initialize once in memory.
so when we close app objects destroy but static variable not destroy. But when we clear app then class destroy and so static variable also. Sometime android kill class due to free memory space in that case static variable destroy.
Upvotes: -2
Reputation: 9643
Android has concept of empty process which says your app may not be removed from memory if it is frequently used by the user even if all its components are destroyed(activities, services, and/or broadcast receivers) , in which case static variables will not be cleared of completely.
Application class is the best way to share some temporary variables between components because application class will be created properly on application startup time and will be cleared of once user exits app.
Upvotes: 0
Reputation: 17580
Static variables are associated with a class and they will live as long as the class is in the memory,and destroy when class gets unloaded (which very rarely happens).
In Android you have seen that when we close any application it does not close completely, It remains in the recent application stack, That you can see by holding in the home button(On Most Devices).
Android itself kicked out those recent app when the other app needs memory
Upvotes: 25
Reputation: 1006789
Can I still access the content of the variable?
Assuming that by "destroyed" you mean something like the user pressing BACK, yes.
Static data members live for the life of the process.
For example to always access a AsyncTask which I store to this variable? What I want is to be able to access to it also after an orientation change.
That is not an appropriate solution. Use a retained fragment, or use onRetainNonConfigurationInstance()
.
Upvotes: 4
Reputation: 4703
If the process is killed then all static variables will be reinitialized to their default values.
This is mainly because, when you restart the application, a new instance is created and the static variable will be reinitialized.
Upvotes: 9