androidapplicationcontext

Get application context returns null


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;
    }
}

Solution

  • 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>