In an Android app, is there anything wrong with the following approach:
public class MyApp extends android.app.Application {
private static MyApp instance;
public MyApp() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
and pass it everywhere (e.g. SQLiteOpenHelper) where context is required (and not leaking of course)?
There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.
In particular you should be careful when dealing with anything that deals with the
GUIthat requires aContext. For example, if you pass the application Context into theLayoutInflateryou will get an Exception. Generally speaking, your approach is excellent: it’s good practice to use anActivity'sContextwithin thatActivity, and theApplication Contextwhen passing a context beyond the scope of anActivityto avoid memory leaks.Also, as an alternative to your pattern you can use the shortcut of calling
getApplicationContext()on aContextobject (such as an Activity) to get the Application Context.