Get application context returns null
Create a static instance of the Context
in your OnCreate
and keep it till you want to get it from
a getter method getContext()
From the Application
class:
public class MyApp extends Application {
private static Context sContext;
@Override
public void onCreate() {
sContext = getApplicationContext();
super.onCreate();
}
public static Context getContext() {
return sContext;
}
}
Declare it in your Manifest
:
<application android:name="com.package.name.MyApp">
Create in onCreate()
an instance of getApplicationContext()
(mContext
) then call MyApp.getContext()
from everywhere in your app and you will get your application context statically.
public class MyApp extends Application {
private static Context mContext;
public static Context getContext() {
return mContext;
}
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
}
Remember to declare into your AndroidManifest.xml
<application android:name="com.mypackage.mypackage.MyApp">
...
...
...
</application>