My app uses several helper classes with static methods that need a context and for that I've created an "ApplicationContext" class as follows:
import android.app.Activity;
import android.content.Context;
public class ApplicationContext {
private Context appContext;
private static ApplicationContext instance;
private ApplicationContext(){}
public void init(Context context)
{
appContext = context;
}
private Context getContext()
{
return appContext;
}
public static Context get()
{
return getInstance().getContext();
}
public static Activity getActivity()
{
return (Activity)getInstance().getContext();
}
public static Context getApplicationContext()
{
return get().getApplicationContext();
}
public static ApplicationContext getInstance()
{
return instance == null ? instance = new ApplicationContext(): instance;
}
}
and in every activity onCreate method I set the current context like this:
ApplicationContext.getInstance().init(this);
and with this, I can get an instance of the current context or activity wherever I need it as follows:
ApplicationContext.get();
ApplicationContext.getActivity();
and all is working fine, but I'm not really sure if this is considered a good practice or not.
Another option is just to declare a static context like follows:
public WeakReference<Context> context;
in -non activity- classes where I need it, set it in activities that uses that classes like this:
whateverclassname.context = this;
and access it like
if (context!=null) ... context.get()
First, I'd like to know if first approach is good practice or not, then, if it is not, I'd like to know which of the two is best or any advice on how to handle the need of a context in non-activity classes.