Why getApplicationContext() in constructor of Activity throws null pointer exception?
Solution 1
Wait for the end of onCreate
to call this method.
public class MainActivity extends BaseActivity {
public onCreate(Bundle savedInstanceState) {
super(savedInstanceState);
getApplicationContext(); //activity has a context now
}
}
Solution 2
Just to get a feeling of what's going on. Activity extends ContextThemeWrapper which extends ContextWrapper from whom Activity inherits getApplicationContext()
. ContextWrapper implements it as :
@Override
public Context getApplicationContext() {
return mBase.getApplicationContext(); // mBase is a Context
}
The only public constructor of ContextWrapper
is :
public ContextWrapper(Context base) {
mBase = base;
}
in ContextThemeWrapper
we have :
public ContextThemeWrapper() {
super(null);
}
and since Activity does not define an explicit constructor the constructor above is called - mBase == null
in Activity's constructor - boom.
Links from 4.2.2_r1
Mr_and_Mrs_D
Be warned - the Monster isAlife Git, Java, Android and finally Python I was flirting with JEE since a couple years but since 1/2014 we are having an affair I spent the best part of the last year refactoring a widely used mod manager application. Here is the commit message of the release I have been working on, where I detail what I have been doing: https://github.com/wrye-bash/wrye-bash/commit/1cd839fadbf4b7338b1c12457f601066b39d1929 I am interested in code quality and performance (aka in the code as opposed to what the code does) If you find my posts useful you can buy me a coffee TCP walks into a bar & says: “I’d like a beer.” “You’d like a beer?” “Yes, a beer.”
Updated on July 29, 2022Comments
-
Mr_and_Mrs_D almost 2 years
After some time spent bug hunting it turns out that :
public class MainActivity extends BaseActivity { // BaseActivity extends Activity public MainActivity() { super(); getApplicationContext(); // NPE here } }
Why ? Where is this documented ?
Froyo -
Mr_and_Mrs_D about 11 yearsI found out - my problem is not that
getApplicationContext();
returns null but that it throws. Where is this documented is my question - and possibly some theory on the matter :) - I believe many have fell to the lack of docs on this one - would qualify for a bug report -
Snicolas about 11 yearsCheck at the source code of Activity. My guess is that a context will be called and generate the NPE.
-
Snicolas about 11 years
-
Snicolas about 11 yearsYou misunderstood the link. This is the impl inherited by Activity.
-
Mr_and_Mrs_D about 11 years
return mBase.getApplicationContext();
click -->public abstract Context getApplicationContext();
:D -
Mr_and_Mrs_D about 11 yearsFound some time to walk through the code - why is how, better :)
-
Ben Akin almost 6 yearsMore help, if you want to set up your buttons in this activity, you should set them up in a function outside of onCreate and then call that set up function after
context = getApplicationContext();