8

I am posting this question in the hope that I can get some kind of definitive answer.

Is it really impossible to access resources without an activity or context reference. Passing around such references when all that is required is to access some values or assets or strings which have nothing to do with the UI makes for overly complicated code.

Plus all those potential hanging references.

Also this completely ruins various Design Patterns such as singletons, having to supply parameters when getting the instance.

Putting a static reference

So is there a way or does the whole community just live with this problem.

bogflap
  • 121
  • 2
  • 5

3 Answers3

9

Your resources are bundled to a context, it's a fact and you can't change that.

Here's what you can do:

Extend Application, get the application context and use that as a static helper.

public class App extends Application {

    private static Context mContext;

    public static Resources getResources() {
        return mContext.getResources();
    }

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }
}

Your manifest:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name="your.package.path.to.App">
Knickedi
  • 8,742
  • 3
  • 43
  • 45
  • An alternative approach would be to have activities load the resources and then pass those as parameters to other objects instead of passing a context object. But this pattern is what I use. :) – i_am_jorf Sep 23 '11 at 16:33
  • 1
    seems like we can't call the method `getResources` since there already exists a non-static member method called `getResources` inherited from `ContextWrapper`, [see here](https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/ContextWrapper.java#L83) – sled Dec 01 '14 at 20:19
  • rename `getResouces()` to `getResourcesSafe()` or something – ChrisMcJava Jul 18 '15 at 23:12
0

I guess you could use context from some UI element like textView.getContext() if the other responses don't work for you.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 02 '22 at 11:45
0

Make your Application class a singleton and use that. It is a Context. All resources are tied to your app, so you need a Context reference. You can pre-load strings, etc. in a singleton class if you don't want to load them dynamically.

Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84