To access a string in the main class the getString()
method works very well. but what if we have created another class and need access to the strings?
I tried Resources.getSystem().getString(R.string.m1);
but this didn't work and caused the app to crash.
any suggestion?
thank you.

- 765
- 6
- 24
4 Answers
You can do it like this:
String m1 = this.getResources().getString(R.string.m1);

- 6,627
- 5
- 44
- 57
There are many ways to do that, I'll tell you mine.
Whenever I need to access some resource, I pass a Context
as a parameter for the method.
Using a context
variable, you can get resources like this:
context.getResources().getString(R.string.my_string);

- 2,140
- 1
- 17
- 31
If the class is a Context, use getResources()
. If it's not, then you need to pass it an instance of Resources
from one of your own Context
s. Resources.getSystem()
returns a Resources object for the Android system, so it has Android's resources, not yours.

- 38,365
- 12
- 84
- 104
getString()
is a method of the Context
class, so you need to pass the Context (e.g. the Activity object) to the other class. Than you can call contextObj.getString()
.
See the Context class documentation for more information.
A "quick and dirty" solution could be a static Context variable where you can assign the main Activity object at start time, but I don't suggest this way.

- 15,478
- 6
- 74
- 115