I have several classes in my application that uses the Context
object to access SharedPreferences and serialize files. Simply put, I want to know how to "design away" the Context.
The background to why I want to do this is because:
- The classes should be created in the
onCreate()
method of aFragment
(and the Context is not decided at this point) - It's just plain ugly to pass around the Context all the time. Especially since I use Singleton-reminding instantiation of these classes (Don't judge, please)
- The specific context isn't really needed here, so it should be possible to design away... (What I mean is that I only need the Application Context)
An example of why this is ugly is my Cache
object. It holds cached values downloaded from 1-5 different sources decided at runtime.
public static Cache getInstance(Context context) {
if(instance == null) {
instance = new Cache(context);
}
return instance;
}
When later using this object, it needs to read a SharedPreference
which needs the Context
, so it has to be passed around every single time I want to get an instance of the Cache
.
So how can I get rid of these ridiculous contexts? Using the Application Context
should be just fine... I guess that the problem can be boiled down to something like "How do I get a SharedPreferences object" in an object without a specific Context?"