I’ve been experimenting with extending Application as a quick way of getting hold of the Application Context object. I have a class like so:
public class PageMonitorApplication extends Application
{
@Override
public Context getApplicationContext()
{
return super.getApplicationContext();
}
}
And my manifest includes:
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".PageMonitorApplication">
However, when creating an instance of PageMonitorActivity and calling getApplicationContext() I get a null pointer exception. Whilst debugging in eclipse and inspecting the instance of PageMonitorActivity, I can see that base=null.
Can anyone advise what is wrong?
super.getApplicationContext()is returningnullbecausePageMonitorApplicationis the application context. You should check ifgetApplicationContextreturnsnull, and if so, just use theContextyou already have.To get a reference to
PageMonitorApplication, callgetApplicationContexton the currentActivityorService(or otherContextyou may have).