3

I have all my strings for my project stores in the string.xml file. I have no problem using them in most cases but for some reason it outputs an integer value to the editText when I mix Strings with an integer for example if I do:

editText.setText(R.string.x_plays + j)

which I want to display "X Plays: 3" to the GUI however it displays a large integer to the GUI. If I do this without j (which is an integer) it is fine.

editText.setText(R.string.x_plays)

This just displays the string "X Plays: ".

So the problem is obviously trying to concatenate an integer with an R.string but I don't know how to work around this. I have tried using stringBuilder and adding in empty strings ("") around the R.string and integer but similar results are returned. How can I fix this?

3 Answers 3

2

The reason why this happens is because R.string.x_plays is actually an integer resource ID that certain methods are able to convert into a string that can be displayed. One of these is setText. However, if you add a number to this ID, it may no longer be valid.

The easiest solution is to just write getString(R.string.x_plays) + j.

You could also change the string to a format string, such as X plays: %1$d and instead write getString(R.string.x_plays, j)

See: String Resources

Sign up to request clarification or add additional context in comments.

2 Comments

It does not recognize the getString(R.string.x_plays) method. I am using android studio and it does not even ask me to import
If you're in an activity, getString() should work; otherwise you need to obtain a context object, for example getActivity().getString() in a Fragment
1

Use getString instead. Since you want to concatenate the String, get the String and concatenate:

getString(R.string.blah);

Actually R.string.something is an integer (a reference).

editText.setText(int)also takes this int value as a parameter. You can also send string as a param to setText. But first you would have to get the string in string.xml as string using getString() function.

1 Comment

It does not recognize a getString() method?
1

You can use string format argument for cases when you want to join a static string (from string.xml) with your dynamic values (like i);

in Strings.xml

<string name="jump_message">I jumped from %1$d storey building</string>

in code

int i = 99;
String finalMessage = String.format(getString(R.string.jump_message), i);
//finalMessage becomes 'I jumped from 99 storey building'

1 Comment

I think it's more concise to pass the format arguments directly to getString—e.g. getString(R.string.jump_message, i). Not sure why the Android docs don't mention this...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.