1

I am trying to display a text that i set in TextView. I have already assigned a string in strings.xml with the name operator_mixed

Strings.xml

<string name="operator_mixed">%d  %s %d  %s %d</string>

And in my initialize.java file i tried to refer to this string, but it doesn't display anything.However when i try to display text without any formatting it kinda works ,but i know concatenating strings in textview is not preferable.

Initialize.java

textview.setText(getString(R.string.operator_mixed, a1, operator1, a2, operator2, a3));

Where a1, a2, a3 are integers and operator1, operator2 are strings.

Is there any problem with my code?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Ramu
  • 147
  • 1
  • 13

3 Answers3

0

Try with below

<string name="operator_mixed">%d  %s %d  %s %d</string>
textview.setText(String.format(getString(R.string.operator_mixed),a1,operator1,a2,operator2,a3)));

You have to use String.format()

Zoe
  • 27,060
  • 21
  • 118
  • 148
Mehul Kabaria
  • 6,404
  • 4
  • 25
  • 50
  • Have you tried using a debugger to check the line is executed ? This code is supposed to work. Maybe the line is simply not executed ? – Arthur Attout Apr 19 '19 at 07:50
  • yeah i have checked, it works . when i try to setText like this **textview.setText(getString(R.string.operator_mixed))** it works ,it displays the text in operator_mixed in strings.xml directly.but it deosnt work when i tried to do like above suggested answer @Arthur Attout . – Ramu Apr 19 '19 at 07:51
0

I just tried this code in my app.

string.xml: (Same as yours)

<string name="operator_mixed">%d  %s %d  %s %d</string>

MyActivity.java

int a1 = 10;
int a2 = 20;
int a3 = 30;
String operator1 = "Operator 1";
String operator2 = "Operator 2";

my_txt_title.setText(getResources().getString(R.string.operator_mixed, a1, operator1, a2, operator2, a3));

It's working fine.

enter image description here

Zoe
  • 27,060
  • 21
  • 118
  • 148
Ajay Mehta
  • 843
  • 5
  • 14
  • I know that is the correct syntax and i know it should work ,bt i assume there is some problem with the android studio syncing files or something like that.Am sure the code is perfect as it displays the string directly inserted into it .Thank you for the help I will look on to it.Somehow it displays exact text in strings.xml when i do this . **textview.setText(R.string.operator_mixed)** – Ramu Apr 19 '19 at 08:08
0

I figured it out. I just need to pass a Context like this:

textview.setText(c.getResources().getString(R.string.operator_mixed, a1, operator1, a2, operator2, a3))

here c is the context of MainActivity.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Ramu
  • 147
  • 1
  • 13