views:

224

answers:

1

I've been racking my head with this...

I've got a localized strings.xml file in a values-en folder with this example string: @string/my_string

The string has the following text stored in English: "My String"

When accessing the localized string via a layout, it works fine.

When I try to change it in code, that's where I get problems.

I store the string into an array of strings for later use. The 'context' is passed from my activity to a data class and used with this line of code:

dataStrings = new String[] { (String) context.getResources().getString(R.string.my_string) };

Later, I try to display this string, like so:

buttons[0].setText(dataStrings[0]);

It displays:

@string/my_string

How do I get it to display the string without '@string/', the proper localized string?

+1  A: 

You can run getString() directly on the Context object; you don't need to run getResources(). However, this should do the same thing as you're currently doing so I don't think that's the source of your problem.

The first thing to confirm is that what you think is happening is happening. Either use the debugger to check that buttons[0] contains "@string/my_string" or try calling setText() with a hard-coded value to make sure the text is actually being updated on the correct button - e.g. buttons[0].setText("StackOverflow!");

Dave Webb
Thanks Dave!After checking the string contents, I've noticed that I'm using an incorrect array index (the array was much larger than the example posted).Also, thanks for the heads up on the context object. Is there any way to call it statically, without having to pass in a context?I tried:Context.getResources().getString(R.string.my_string)But I can't use is on a non-static method.
cray_ze_coder
I'm assuming you need to run it on a Context as that's how it knows which locale to get the string for. I have the same thing as you - utility classes where the first argument to each method is always a Context. Also, if my answer is correct you should accept it by clicking on the tick. You can read all about accepting answers here: http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about
Dave Webb
Your answer was perfect. I clicked the 'tick' - I've not posted on StackOverflow before. Thanks again.
cray_ze_coder