Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getString Outside of a Context or Activity

I've found the R.string pretty awesome for keeping hardcoded strings out of my code, and I'd like to keep using it in a utility class that works with models in my application to generate output. For instance, in this case I am generating an email from a model outside of the activity.

Is it possible to use getString outside a Context or Activity? I suppose I could pass in the current activity, but it seems unnecessary. Please correct me if I'm wrong!

Edit: Can we access the resources without using Context?

like image 487
SapphireSun Avatar asked Nov 23 '10 06:11

SapphireSun


2 Answers

Yes, we can access resources without using `Context`

You can use:

Resources.getSystem().getString(android.R.string.somecommonstuff) 

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

like image 145
Gangnus Avatar answered Oct 14 '22 17:10

Gangnus


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.

like image 29
Erich Douglass Avatar answered Oct 14 '22 16:10

Erich Douglass