1

I´m programming with Java in Android Studio.

I just don´t get it, why this happens:

The result of my setText() method is always the same: "0" is shown as buttontext.

The setText method of my button:

button_adj1.setText(String.valueOf(getResources().getIdentifier("adj"+ counter,"String", getPackageName())));

The counter variable works correctly and gets incremented after click, which should extract the counter+1 item at second click.

If I replace counter with e.g. 3, the result is also 0.

Hardcoded attempt:

button_adj1.setText(String.valueOf(getResources().getIdentifier("adj"+ 3,"String", getPackageName())));

The resource file: res/strings.xml:

<string name="adj1">Test0</string>
<string name="adj2"Test1</string>
<string name="adj3">Test2</string>
<string name="adj4">Test3</string>
<string name="adj5">Test4</string>
<string name="adj6">Test5</string>
<string name="adj7">Test6</string>
<string name="adj8">Test7</string>
<string name="adj9">Test8</string>
<string name="adj10">Test</string>

Is there any other possible way?

I thought String.valueOf is converting the result of getResources.getIdentifier into string?

Elletlar
  • 3,136
  • 7
  • 32
  • 38
Dorian Feyerer
  • 258
  • 5
  • 14
  • Does this answer your question? [java android getResources().getIdentifier()](https://stackoverflow.com/questions/16862000/java-android-getresources-getidentifier) – f1sh Nov 13 '20 at 22:47
  • Thank you for your advice. Solution below worked for this case – Dorian Feyerer Nov 14 '20 at 07:33

1 Answers1

1

Try changing it from:

button_adj1.setText(String.valueOf(getResources().getIdentifier("adj"+ counter,"String", getPackageName())));

To:

button_adj1.setText(getResources().getIdentifier("adj"+ counter,"string", getPackageName()));

The changes:

  1. Use "string" not "String" in the call to getIdentifier() -> This solves the issue with the TextView being set to 0
  2. Remove valueOf and instead pass the resource ID of the string to setText() -> This prevents the TextView being set to 2131755036 for example

setText() has a couple of different overloads. But you want to ensure that this one is invoked:

public final void setText (int resid)

Not this one:

public final void setText (CharSequence text)

If on the other hand you want to use the latter overload, then getString() must be called passing the integer value of the resource ID.

TextView Docs

Elletlar
  • 3,136
  • 7
  • 32
  • 38