Will saving the activity to a static variable guarantee that its existing elements will not be garbage collected and that the variables in the activity will still be accessible?
Asked
Active
Viewed 558 times
1
-
why do you want that in the first place? – Raghunandan Dec 12 '14 at 10:08
-
@Raghunandan I want to retrieve the previous states when I get back to the original screen. – damat-perdigannat Dec 12 '14 at 10:14
-
1Officially, you'd use [`onSaveInstanceState()`](http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle%29) and [`onRestoreInstanceState()`](http://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState%28android.os.Bundle%29) for this. – JimmyB Dec 12 '14 at 10:20
-
@b16db0 for that you don't need to do what you are doing. Also take care of out of memory exceptions – Raghunandan Dec 12 '14 at 11:16
-
possible duplicate of [Are static fields open for garbage collection?](http://stackoverflow.com/questions/453023/are-static-fields-open-for-garbage-collection), or perhaps, more specifically, [is it possible for Android VM to garbage collect static variables without killing the whole Android application?](http://stackoverflow.com/questions/19824691/is-it-possible-for-android-vm-to-garbage-collect-static-variables-without-killin) – corsair992 Dec 12 '14 at 16:36
1 Answers
1
No, Static variables maynot persist forever.
Use SharedPreferences
to persist variable values and activity state.
You can also try onSaveInstanceState()
and onRestoreInstanceState()
methods as explained below.
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
You can read more from here

Darish
- 11,032
- 5
- 50
- 70
-
-
-
As long as the app runs, the static variable will be inside the VM. – damat-perdigannat Dec 12 '14 at 10:24
-
you can save the variable values into SharedPreferences on onPause() method and restore them on onResume(). Also you can store the activity state using onSaveInstanceState() and onRestoreInstanceState() methods. – Darish Dec 12 '14 at 10:27