In my android project, I have ImageAdapter class in which I pass app context for some further needs.
public class ImageAdapter extends BaseAdapter {
private Context c;
public ImageAdapter(Context c) {
this.c = c;
}
...
}
The problem is that I wanna make ImageAdapter as a singleton to have an easy access to the instance of this class from all of my activities. But I have no idea how to pass app context from getApplicationContext() method from one of my activities to ImageAdapter. So is there any "magic" to do that as follows?
public class ImageAdapter extends BaseAdapter {
private Context c;
private static class Holder {
public static final ImageAdapter IA = new ImageAdapter();
}
private ImageAdapter() {
this.c = /* some magic here */.getApplicationContext();
}
public static ImageAdapter getInstance() {
return Holder.IA;
}
...
}
Maybe you have some other ideas for sharing ImageAdapter for any of my activities. I'm a newbie to android and I'm a little bit confused with the ways of passing data among activities.
I will be grateful for any help.
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" >