0

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.

Hadi Aghandeh
  • 765
  • 6
  • 24

4 Answers4

0

You can do it like this:

String m1 = this.getResources().getString(R.string.m1);
Hussein El Feky
  • 6,627
  • 5
  • 44
  • 57
0

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);
Paulo Avelar
  • 2,140
  • 1
  • 17
  • 31
0

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 Contexts. Resources.getSystem() returns a Resources object for the Android system, so it has Android's resources, not yours.

Karakuri
  • 38,365
  • 12
  • 84
  • 104
0

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.

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115