2

Is this the right way to set text in TextView programmatically?

points_txt.setText(R.string.you_have + current_points + R.string.points);`

It shows me a ResourcesNotFoundException error for the string while I can see the string in the strings.xml file.

jay.sf
  • 60,139
  • 8
  • 53
  • 110

6 Answers6

6
points_txt.setText(getResources().getString(R.string.you_have) + current_points + getResources().getString(R.string.points));
Raj
  • 2,997
  • 2
  • 12
  • 30
1

You get a ResourcesNotFoundException because you're adding int values (resource identifiers are mapped to int values at compile time) instead of concatenating Strings.

The sum of the various resource identifiers might even be another valid resource identifier, but that would only happen accidentally. Nevertheless, if you pass an int value into setText(), the runtime tries to find a string resource by that number. In your case, it failed and so your app crashed.

So you have to get the Strings first and concatenate them afterwards:

points_txt.setText(getString(R.string.you_have) + current_points + getString(R.string.points));
Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61
1

points_txt.setText(R.string.you_have + current_points + R.string.points);

This is showing "ResourcesNotFoundException" because "R.string.you_have" is an integer value an "current_point" variable also is an int type

setText() requires the String type...

to get string value of "R.string.you_have" you can use

getResources().getString(R.string.you_have);
points_txt.setText(getResources().getString(R.string.you_have) + current_points + getResources().getString(R.string.points));
Chuk Ultima
  • 987
  • 1
  • 11
  • 21
0

To get a string from strings.xml do this:

String you_have = getResources().getString(R.string.you_have);
0

You are almost there but I feel might be behind a few steps but not sure about this since you haven't shared all of your code.

You need to wire in the TextView first between your Java class and XML

TextView tv1 = (TextView)findViewById(R.i.d.textView1)

Next is setting the String for the textview

tv1.setText(getResources().getString(R.string.you_have) + "current_points" + getResources().getString(R.string.points));

You are basically missing the " " marks which are compulsory when you are assigning hardcoded string.

Nero
  • 1,058
  • 1
  • 9
  • 25
0

You must firstly parse that resource to string:

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

More about that here: how to read value from string.xml in android?

So answer for your question will be literally as following:

String you_have = getString(R.string.you_have);
String points = getString(R.string.points);

points_txt.setText(you_have + current_points + points);