Get application context from non activity singleton class
Update: 06-Mar-18
Use MyApplication
instance instead of Context
instance. Application
instance is a singleton context instance itself.
public class MyApplication extends Application { private static MyApplication mContext; @Override public void onCreate() { super.onCreate(); mContext = this; } public static MyApplication getContext() { return mContext; }}
Previous Answer
You can get the the application context like this:
public class MyApplication extends Application { private static Context mContext; @Override public void onCreate() { super.onCreate(); mContext = getApplicationContext(); } public static Context getContext() { return mContext; }}
Then, you can call the application context from the method MyApplication.getContext()
Don't forget to declare the application in your manifest file:
<application android:name=".MyApplication" android:icon="@drawable/icon" android:label="@string/app_name" >
I'd rather pass a context instance as a parameter to every method in singleton which really needs it
APPROACH #1:
Since you specify that ImageAdapter is a singleton, one simple answer is to create that singleton from a class that has access to app context:
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); ImageAdapter.createIt(this); }}public class ImageAdapter extends BaseAdapter { private static ImageAdapter it; // Get the singleton. public static ImageAdapter getIt() { return it; } // Call this once, to create the singleton. public static void createIt(Context context) { it = new ImageAdapter(context); } private final Context c; private ImageAdapter(Context context) { c = context; }}
APPROACH #2:
If it were not a singleton, then I would use the accepted answer. In that case, remove the local variable from ImageAdapter, because context can always be obtained from MyApplication. Expanding on the accepted answer, if you want a local method as a convenience, define ImageAdapter.getContext(). Complete solution:
public class MyApplication extends Application { private static Context appContext; public static Context getContext() { return appContext; } @Override public void onCreate() { super.onCreate(); appContext = this; }}public class ImageAdapter extends BaseAdapter { public ImageAdapter() { } // [Optional] Call this whenever you want the app context. private Context getContext() { return MyApplication.getContext(); }}