Search code examples
inner-classessoundpoolandroid

Two onCreate() methods in Android?


I am working off another example (found here Loading MP3s into the Sound Pool in Android). but for some reason I am ending up with two onCreate() methods and if I delete one I am getting errors.

I am trying to load the MP3s into the Soundpool once and then call them in other activities.

My code:

class MyApp extends Application {
    private static MyApp singleton;

    private static SoundPool mSoundPool;

    public onCreate() { // ##### Deleting this gives me errors ###, not deleting it gives me 1 error.
         super.onCreate();
         singleton = this;
         mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);// Just an example
    }

    public static MyApp getInstance() {
         return singleton;
    }

    public SoundPool getSoundPool() {
         return mSoundPool;
    }
}


public class TestAndroidGlobalsActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Solution

  • Your code only has one onCreate method per class. They serve different purposes and are called when each of those classes is created by the OS.

    Your MyApp.onCreate is called when the application is created and sets up application-wide state inside your MyApp class.

    Your TestAndroidGlobalsActivity.onCreate is called when the Activity is created and sets the state for that specific activity an initializes its UI.