I've gotten a number of crash reports with the following stack traces (names changed):
Caused by: java.lang.InstantiationException: can't instantiate class com.example.MyApplication; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newApplication(Instrumentation.java:997)
at android.app.Instrumentation.newApplication(Instrumentation.java:982)
at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
... 11 more
java.lang.RuntimeException: Unable to instantiate application com.example.MyApplication: java.lang.InstantiationException: can't instantiate class com.example.MyApplication; no empty constructor
at android.app.LoadedApk.makeApplication(LoadedApk.java:501)
android.app.Application
has an explicit parameterless constructor:
public Application() {
super(null);
}
MyApplication
inherits from android.app.Application
and has no explicit constructors at all. According to my understanding of the Java spec, this means that the following constructor should be implicitly inserted by the compiler:
public MyApplication() {
super();
}
This must have happened, or I'd never have been able to compile the app in the first place. So what could be causing these crashes?
MyApplication.class
with javap
:
Compiled from "MyApplication.java"
public class com.example.MyApplication extends android.app.Application {
public com.example.MyApplication();
Signature: ()V
public void onCreate();
Signature: ()V
public void onLowMemory();
Signature: ()V
public void onTrimMemory(int);
Signature: (I)V
// ... some other methods ...
static {};
Signature: ()V
}
The default constructor is definitely in there, and it's public.
Note: this turned out not to be the issue in this case, but if you're reading this question because you've faced the same symptom, it could be the issue for you...
According to my understanding of the Java spec, this means that the following constructor should be implicitly inserted by the compiler
public MyApplication() { super(); }
That's only the case if it's a public class. From section 8.8.9 of the JLS:
The default constructor has the same accessibility as the class (ยง6.6).
So if your class is declared as having any access other than public
, the constructor won't be public either.
You haven't shown your class declaration, but the first thing you should check is that it's public.
See more on this question at Stackoverflow