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.
The Android resource system keeps track of all non-code assets associated with an application. You can use this class to access your application's resources. You can generally acquire the Resources instance associated with your application with getResources() .
In android, Context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the Context class.
Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more. You should always externalize app resources such as images and strings from your code, so that you can maintain them independently.
Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With