java.util.MissingFormatArgumentException: Format specifier '%2$s

Viewed 453

i have string

<string name="data">%1$s / %2$s</string>

i pass varargs in function like that

fun getText(varargs text: String) : String {
    return getString(R.string.data,text)
}

I called function in the activity

getText("1" ,"2")

It gives error

E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.vivek, PID: 5126
  java.util.MissingFormatArgumentException: Format specifier '%2$s'
    at java.util.Formatter.format(Formatter.java:2529)
    at java.util.Formatter.format(Formatter.java:2459)
    at java.lang.String.format(String.java:2911)
2 Answers

The accepted answer actually does not solve the issue, so I'm not really sure why it's accepted.

It doesn't matter whether you use String.format, Context.getString or Fragment.getString or Resources.getString. The problem is in how the varargs argument is interpreted. Seems like a Kotlin thing. Simply put, it takes the whole varargs as an array as if it was a single object and passes that as one of the varargs arguments to the function you call within your function.

So in order to make Kotlin not do that, you just need spread the varargs argument with an asterisk (the so-called Spread Operator), like so:

fun getText(varargs text: String) : String {
    return getString(R.string.data, *text)
}

This is a tested solution.

Use like this:

fun getText(varargs text: String) : String {
    return String.format(getResources().getString(R.string.data), text)
}
Related