0

In the onCreate() method I load a list of levels. This is stored in a singleton structure (using an enum for this). When I press the back button and return again, the list is still there and all the levels are added again. I don't understand why this is happening, since the Activity Lifecycle states that the process is killed before onCreate() is called again.

Why is this happening?

edit, some code:

In separate file:

public enum GameInformation {
   INSTANCE;
       public List<Level> levelSet;

       public void loadLevelSet(Context context) {
       ...
       }
}

In main activity:

public void onCreate(Bundle savedInstanceState) {
    GameInformation.INSTANCE.loadLevelSet(this);
}
Ben Ruijl
  • 4,973
  • 3
  • 31
  • 44
  • Is the "Singleton structure" statically accessible outside the Activity? – Cephron Jul 27 '11 at 17:00
  • Anyone else think using enums like this is totally weird? – Josh Jul 27 '11 at 19:25
  • @Josh It's the recommended way for a singleton, see Effective Java by Joshua Bloch or [this](http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java). – Ben Ruijl Jul 28 '11 at 08:58
  • @Ben - Crazy. Guess it's time to go refactor all my singleton code. – Josh Jul 28 '11 at 13:04

2 Answers2

7

I don't understand why this is happening, since the Activity Lifecycle states that the process is killed before onCreate() is called again.

No, it does not.

The process is most certainly not killed immediately when your last activity is destroyed via the BACK button. Android will keep the process around, even if you have no active components, in case the user happens to want to return quickly to the app. Later on, when Android needs RAM, it will then terminate the process.

You should not be making any assumptions whatsoever as to whether static data members will or will not be there. Just lazy-initialize them if they are null.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

To use the back button does not kill the application. It only sets it to the background. The application is actually killed by the system when it is detected as dormant, later.

So your levels are simply reloaded by the OnCreate() method when you come back to your app.

Shlublu
  • 10,917
  • 4
  • 51
  • 70