Search code examples
androidstringstring.formatinvocationtargetexception

Android - String.format - MissingFormatArgumentException and InvocationTargetException


I have the following code-block -

strBody = String.format(getString(R.string.some_string,
                                    strPropertyName,
                                    "some string"
                                                        )
                                              ); 

while R.string.some_string is of this form -

some words \'%1$s\' more words. %2$s

but i get the following exception on some devices -

Caused by: java.lang.reflect.InvocationTargetException
1   java.lang.reflect.Method.invokeNative   
2   java.lang.reflect.Method.invoke Method.java, line 515
3   android.view.View$1.onClick View.java, line 3949
... 11 more
Caused by: java.util.MissingFormatArgumentException: Format specifier: d
1   java.util.Formatter.getArgument Formatter.java, line 1111
2   java.util.Formatter.doFormat    Formatter.java, line 1076
3   java.util.Formatter.format  Formatter.java, line 1042
4   java.util.Formatter.format  Formatter.java, line 1011
5   java.lang.String.format

Solution

  • it should be either

     strBody = String.format(getString(R.string.some_string), 
                  strPropertyName, item.getString(ObjKombiItem.FIELD_PERMALINK)); 
    

    or

     strBody = getString(R.string.some_string, 
                      strPropertyName, item.getString(ObjKombiItem.FIELD_PERMALINK)); 
    

    the first version uses String.format to apply the parameter to the String referenced by R.string.some_string. The second version does the same thing, but use directly getString(int resId, Object...objs). What you are missing, in your case, is a bracket before the first comma:

    getString(R.string.some_string,
    

    should be

    getString(R.string.some_string),