Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Strings Parameters Count Error

Tags:

string

android

I have a string in my string.xml:

<string name="date_time_short">%2$d.%2$d. %1$s %2$d:%2$d</string>

Now i want to set the values from code:

String.format(context.getResources().getString(R.string.date_time_short), day, month, at, hour, minute);

But i get the error:

Wrong argument count, format string date_time_short requires 2 but format call supplies 5

So it seems to has a problem with %1$s which represents a string. At least this is written in the documentation here

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

So why am i getting this error?

like image 913
Mulgard Avatar asked Dec 06 '25 07:12

Mulgard


2 Answers

The number in %1$s for example indicates the index in your Object... argument. So in your example, the correct definition of the string would be :

<string name="date_time_short">%1$d.%2$d. %3$s %4$d:%5$d</string>
like image 107
Nicolas Mauti Avatar answered Dec 08 '25 20:12

Nicolas Mauti


try this <string name="date_time_short">%1$s.%2$s. %3$s %4$s:%5$s</string>

like image 35
Mohammad Tauqir Avatar answered Dec 08 '25 19:12

Mohammad Tauqir