0

I am developing an app where I have in some parts of code a

textview.setText(R.string.resource1 + progress + R.string.resource2);

but when I run the app, instead of showing the strings as words (these are words translated in some languages) the app shows something like in the textview

  2131755168 106(this is okay, is the variable progress) 62131755102

those numbers should be words in English

Mauro Stancato
  • 537
  • 1
  • 9
  • 19
  • 3
    The `resource` is an id (i.e. number) - to fetch the actual string use `getResources().getString(R.string.resource1);` : https://stackoverflow.com/a/7493367/17856705 (which requires a context). – Computable Jun 04 '22 at 14:08

1 Answers1

1

You are getting that result because you are concatenating values with mixed types, the R.string.resource1 is an int lookup value for retrieving text (it's not the text itself). When concatenating, Java will just 'toString' those int values.

You have two options...

Option 1 (Recommended):

Define a string resource that uses format arguments, then pass the progress in. It is cleaner at the call site and more flexible than option 2 below.

<string name="progress_label">Before %1$d After</string>
textView.setText(getString(R.string.progress_label, progress));

Option 2:

This is less ideal because it doesn't allow you to adapt the phrasing (if needed) for the translation.

<string name="progress_before">Before</string>
<string name="progress_after">After</string>
String before = getString(R.string.progress_before);
String after = getString(R.string.progress_after);

textView.setText(String.format("%1$s %2$d %3$s", before, progress, after));
nEx.Software
  • 6,782
  • 1
  • 26
  • 34
  • Thanks much! Your Option 1 served the purpose nicely! On a personal note, that's the stupidest, most BS nonsense I've ever heard. Considering how frequently Kotlin sneers smugly at my explicit type definitions, I would think that maybe - just maybe - it could go way out on a limb and infer that they type being returned from R. _**string**_ might carry with it the possibility of being... oh, I dunno, a _STRING_!? ...but maybe that's just me. Good gods I hate Java. – NerdyDeeds Mar 07 '23 at 23:20