java - getString Outside of a Context or Activity

ID : 10211

viewed : 35

Tags : javaandroidstringandroid-resourcesandroid-contextjava

Top 5 Answer for java - getString Outside of a Context or Activity

vote vote


Yes, we can access resources without using `Context`

You can use:


... everywhere in your application, even in static constants declarations. Unfortunately, it supports the system resources only.

For local resources use this solution. It is not trivial, but it works.

vote vote


Unfortunately, the only way you can access any of the string resources is with a Context (i.e. an Activity or Service). What I've usually done in this case, is to simply require the caller to pass in the context.

vote vote


In MyApplication, which extends Application:

public static Resources resources; 

In MyApplication's onCreate:

resources = getResources(); 

Now you can use this field from anywhere in your application.

vote vote


##Unique Approach


This will work everywhere in app. (Util class, Dialog, Fragment or any class in your app)

(1) Create or Edit (if already exist) your Application class.

import; import android.content.res.Resources;  public class App extends Application {     private static App mInstance;     private static Resources res;       @Override     public void onCreate() {         super.onCreate();         mInstance = this;         res = getResources();     }      public static App getInstance() {         return mInstance;     }      public static Resources getRes() {         return res;     }  } 

(2) Add name field to your manifest.xml <application tag.

<application         android:name=".App"         ...         >         ...     </application> 

Now you are good to go. Use App.getRes().getString(R.string.some_id) anywhere in app.

vote vote


BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;

So 2 basic things to get string visible in the different class:

//make sure you are importing the right R class import your.namespace.R;  //don't forget about the context public void some_method(Context context) {    context.getString(R.string.YOUR_STRING); } 

Top 3 video Explaining java - getString Outside of a Context or Activity