Home » Android » java – custom android.app.Application not firing onCreate event

java – custom android.app.Application not firing onCreate event

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m deriving a custom application from android.app.Application and I can’t get its onCreate event being fired. Here’s the implementation

import android.app.Application;

public class MyApplication extends Application {

    public MyApplication() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}

And here’s how I’m using it:

MyApplication ctrl = new MyApplication();
How to&Answers:

Add following in your AndroidManifest.xml

<application
    android:name="MyApplication"
    android:debuggable="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name">
</application>

then your onCreate() will get fired.

Answer:

I had this issue and found that in my case that the whole issue was phone side. I rebooted the phone and that fixed the issue.

Answer:

Very simple

In your AndroidManifest.xml, within the application tag enter the name of your Application sub-class with it’s path under the android:name attribute.

Example:

<application
...
android:name=".models.custom.BaseApplication"
...
> ... </application>

Answer:

Don’t construct it, get it from Context.

For example from Activity:

MyApplication ctrl = (MyApplication)getApplicationContext();

More info:
Context.getApplicationContext()

Documentation says that onCreate() is

Called when the application is starting, before any other application
objects have been created

Answer:

You don’t actually create instances of your Activities with the newoperator. Instead you start an Intent like this:

Intent start = new Intent(context, Classname.class);
context.startActivity(start);

When creating an object with the new operator, then onCreate never will be called.

[EDIT] When creating Applications with the new operator onCreate won’t be called either[/EDIT] [EDIT2] You could create a static method that returns the application like this:

public static MyApplication getApp() {
    return mInstance;
}
[/EDIT2]

Answer:

As Balaji Mentioned if your still facing issue even after mentioning class name under application tag

<application
    android:name="MyApplication"
    android:debuggable="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name">
</application>

Then try this:

Try and disabling Instant Run and then clean project and Rebuild it and then run again.
It worked for me.
Thanks.