Search code examples
javaandroidstringconcatenation

What is the/one correct approach to use a concatenated value in the setText() method of a button?


I try to use a concatenated value to set the text of a button, because int xp; is calculated at runtime. The only approach that works throws a warning and is maybe bad practice.

Do you have any idea about a better solution?

I´ve tried it in these ways:


1st approach:

public class selectionActivity extends AppCompatActivity implements View.OnClickListener, Serializable {

    private int xp = 2000;
    public int getXp(){
            return xp;
        }

    @Override
    public void onResume() {
        super.onResume();

    Button currentXp1 = findViewById(R.id.currentXp1);

    currentXp1.setText(R.string.praefixXP + String.valueOf(getXp())); }
}

Result:

Compiles but assigns an int / numeric value to the Button.


2nd approach:

public class selectionActivity extends AppCompatActivity implements View.OnClickListener, Serializable {

    private int xp = 2000;
    public int getXp(){
            return xp;
        }

    @Override
    public void onResume() {
        super.onResume();

    Button currentXp1 = findViewById(R.id.currentXp1);

    currentXp1.setText(R.string.praefixXP + (getXp()));}
}

Result:

Throws a Resources$NotFoundException.


3rd approach:

public class selectionActivity extends AppCompatActivity implements View.OnClickListener, Serializable {

    private int xp = 2000;
    public int getXp(){
            return xp;
        }

    @Override
    public void onResume() {
        super.onResume();

    Button currentXp1 = findViewById(R.id.currentXp1);

    currentXp1.setText("XP: " + (getXp())); }
}

Result:

Works, but needs a annotation:

@SuppressLint({"SetTextI18n"})

4th approach:

public class selectionActivity extends AppCompatActivity implements View.OnClickListener, Serializable {

private int xp = 2000;
public int getXp(){
        return xp;
    }

@Override
public void onResume() {
    super.onResume();

Button currentXp1 = findViewById(R.id.currentXp1);

currentXp1.setText(getResources().getIdentifier("praefixXP", "string", getPackageName()) + getXp());}
}

Result:

Throws a Resources$NotFoundException.


strings.xml:

<resources>

    <string name="praefixXP">XP: </string>

</resources>

Solution

  • You need to use

       currentXp1.setText((getResources().getString(R.string.praefixXP)+getXp()));
    

    To get string value from the String resource file we need to use getResources().getString(STRING_ID) and in this case, I'm just concatenating the result of getXp() with the value of the string.

    Feel free to ask if something is unclear