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 t
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 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.
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).