1

i found this problem some time ago, but i solve it using this: getString(), or this: getResources().getString()

but now, for this case, it doesn't works, i think it's because i need to get the string values on a NON ANDROID ACTIVITY CLASS. I need the resource values on a remote connection class, that doesn't extends any kind of activity or service.

how i can acces to the variables from my strings.xml on this normal class?

this is the code where i get the error (it gets an integer, and not the string value)

String a =R.string.totalpermission;
NullPointerException
  • 36,107
  • 79
  • 222
  • 382

3 Answers3

4

Take a look at these two answers (are the same XD):

Just an advice: try to read some basic concepts... it seems you don't understand what the R class is and how to use it. Trust me, you waste less time studying than trying to figure out how things work.

Community
  • 1
  • 1
Cristian
  • 198,401
  • 62
  • 356
  • 264
3

I'll add something to existing answers since I found it very useful.

To get your strings you have to use a Context. Your activity will work just great.

String string = getString(R.string.myString);

But if you have something more complex... for exemple

R.string.result -> "You %1$s %2$d cats"

String result = getString(R.string.result, killed ? "killed": "saved", count);

That would give you a result like that: You saved 10 cats or You killed 2 cats... and so on. You can pass parameters and positional arguments in strings will get replaced by your arguments in getString.

Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99
  • 1
    IMPORTANT: You need to adapt to the new more explicit format as soon as possible (i.e. You %1$s %2$d cats"), or else it won't compile under Gingerbread anymore. – EboMike Dec 13 '10 at 03:21
  • I added an edit, I wasn't sure the new way was backward compatible. I did a test and it seems to work fine in older version of android. Apparently its an old feature that is now enforced. – Loïc Faure-Lacroix Dec 15 '10 at 22:48
1

All Android resources are referenced via a resource ID, like R.string.totalpermission. You can see those numbers in R.java (although there's no reason to ever do that).

In cases of strings, you can easily get those using Context.getString. Bonus: You can even pass optional arguments and add dynamic strings that way. You always have a context - how are you getting called? If you really don't have a context, you can create one for the package your resources are in.

EboMike
  • 76,846
  • 14
  • 164
  • 167