Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Accessing resources without an Activity or Context refeerence

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.

like image 307
bogflap Avatar asked Sep 23 '11 16:09

bogflap


People also ask

What is the use of getResources () in android?

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() .

What is the difference between activity and context in Android?

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.

What are the resources how different types of resources managed in Android explain?

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.

What is Android activity context?

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).


1 Answers

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">
like image 117
Knickedi Avatar answered Sep 29 '22 09:09

Knickedi