Reputation: 3294
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:
onCreate()
method of a Fragment
(and the Context is not decided at this point) 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?"
Upvotes: 0
Views: 52
Reputation: 3294
I have seen the static getContext()
method on the Application object before and I think it's slightly ugly and I wasn't sure that it was "Risk free" and correct. I was just about to implement it when I found this: https://androidcookbook.com/Recipe.seam?recipeId=1218 which basically says that the Application
object in Android can be treated as a Singleton and that I should place my own Singletons inside that object.
It's essentially the same as @Blackbelt 's solution, but gives a slightly nicer vibe!
Upvotes: 0
Reputation: 157467
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?"
Using the Application Context
. For this purpose you can subclass Application, registering it in your AndroidManifest file, and have a method to retrieve it from every where, like a singleton
Upvotes: 1