2

I'm new to code in Android Studio and when i set a integer in a text like this:

textview.setText(String.format("%d",1));

This code give me back a warning:

Implicitly using the default locale is a common source of bugs: Use String.format (Locale,...)

What is the correct code for put an integer in a .setText?

I founded more question on stackoverflow but don't apply to this.

GMX
  • 950
  • 1
  • 14
  • 29

1 Answers1

3

What is the correct code for put an integer in a .setText?

You simply need to convert your int as a String, you can use Integer.toString(int) for this purpose.

Your code should then be:

textview.setText(Integer.toString(myInt));

If you want to set a fixed value simply use the corresponding String literal.

So here your code could simply be:

textview.setText("1");

You get this warning because String.format(String format, Object... args) will use the default locale for your instance of the Java Virtual Machine which could cause behavior change according to the chosen format since you could end up with a format locale dependent.

For example if you simply add a comma in your format to include the grouping characters, the result is now locale dependent as you can see in this example:

System.out.println(String.format(Locale.FRANCE, "10000 for FR is %,d", 10_000));
System.out.println(String.format(Locale.US, "10000 for US is %,d", 10_000));

Output:

10000 for FR is 10 000
10000 for US is 10,000
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • so in what case "%d" is useful? – GMX Oct 27 '16 at 09:00
  • so i can use %d only if i specify the locale language? – GMX Oct 27 '16 at 09:07
  • it is only useful for more complex String format not to print only a primitive type – Nicolas Filotto Oct 27 '16 at 09:07
  • @NicolasFilotto, depends on your primitive type, if you wan't to print some decimal number with a limit decimal length, this is easiest, at least I think ;) – AxelH Oct 27 '16 at 09:10
  • it depends on your context if you want the result to be localized or fixed. A warning is only meant to warn you just in case you are not aware of it, if you know what you are doing you can just ignore it – Nicolas Filotto Oct 27 '16 at 09:10
  • 1
    @AxelH well providing a format is already context specific, you could even provide a format with integers too, but I agree that it is important to mention it to avoid misunderstandings – Nicolas Filotto Oct 27 '16 at 09:12