Get application context returns null

learner picture learner · Feb 24, 2014 · Viewed 58.7k times · Source

The following schema has been touted as the way to get application context from anywhere within my android app. But sometimes doing MyApp.getContext() returns null. I tried changing the schema by removing static from getContext() so that I would do MyApp.getInstance().getContext(). It still returns null. How do I fix this? How do I get my application's context from anywhere within my app?

public class MyApp extends Application {
    private static MyApp instance;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext() {
        return instance.getApplicationContext();
    }

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

Answer

Jorgesys picture Jorgesys · Feb 24, 2014

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 MyApp instance;
 private static Context mContext;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext() {
      //  return instance.getApplicationContext();
      return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    //  instance = this;
     mContext = getApplicationContext();    
    }
}

Remember to declare into your AndroidManifest.xml

<application android:name="com.mypackage.mypackage.MyApp">
...
...
...
</application>