Joakim
Joakim

Reputation: 3294

How to design away the need of Android Contexts

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:

  1. The classes should be created in the onCreate() method of a Fragment (and the Context is not decided at this point)
  2. 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)
  3. 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?"

Upvotes: 0

Views: 52

Answers (2)

Joakim
Joakim

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

Blackbelt
Blackbelt

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

Related Questions