o9s
is a microblog
home archives search feed blogroll


Context Everywhere

I’ve seen this on Stack Overflow, again and again. Don’t do it. It’s wrong.

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() {
        instance = this;
        super.onCreate();
    }

}

This looks like a good solution. You don’t need to pass a context object to instances that need one. You can call MyApp.getContext() from anywhere.

There’s a problem, you would almost always get the wrong kind of context.

This will always return the application context. In most instances, what you want is the activity context. You should only use the application context if you plan on keeping long-lived objects that need a context” Google Blog. A general use of thumb is if you don’t know which context to use, use the activity context.

In conclusion, don’t do this. Pass a context everywhere. Use the activity context unless you have a good reason to use the application context.

Posted on 2018-04-01   #android     #java  






← Next post    ·    Previous post →