1

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?

damat-perdigannat
  • 5,780
  • 1
  • 17
  • 33
  • 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
  • 1
    Officially, 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 Answers1

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