Reputation: 960
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.
Upvotes: 2
Views: 1404
Reputation: 44965
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
Upvotes: 3