0

In my Application subclass, I save a static reference to Context, so that I don't have to pass contexts around in the rest of my code. I just use MyApplication.getAppContext() whenever I need the application Context:

public class MyApplication extends Application {
    private static Context context;

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getAppContext() {
        return context;
    }
}

Is this safe? Is there a possible scenario where MyApplication.getAppContext() returns null?

fhucho
  • 34,062
  • 40
  • 136
  • 186
  • Why are you placing that getter to get the get the application `context`? Check this question for more info: http://stackoverflow.com/q/5018545/119895 – Macarse Aug 11 '13 at 20:33

2 Answers2

2

A static initializer may call the method at class load time before any object instances are created. Also, a class constructor may call the method before the onCreate method has been called, so yes, the method may return null.

Joni
  • 108,737
  • 14
  • 143
  • 193
2

Use it with following statement in mind, you are safe to go!

onCreate() Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

http://developer.android.com/reference/android/app/Application.html

And check following post as well.

Using Application context everywhere?

Community
  • 1
  • 1
pierrotlefou
  • 39,805
  • 37
  • 135
  • 175
  • Ok, great! So it seems that unless I call `MyApplication.getAppContext()` from `MyApplication`'s constructor or static initializer, I'm fine. – fhucho Aug 11 '13 at 12:03