Format string XXX is not a valid format string so it should not be passed to String.format

南楼画角 提交于 2019-12-04 15:32:23

问题


I have android app and this string in resources:

<string name="create_group_select_people">Select up to %1$d people!</string>

This is called from fragment:

Integer countMax = 5; //also tried just "int" - nothing changed
getResources().getString(R.string.create_group_select_people, countMax);

but I got error:

Format string 'create_group_select_people' is not a valid format string so it should not be passed to String.format

I can't understand what is wrong? When I launch app - it shows me literally "Select up to %1$d people!"


回答1:


I just copied the code and it works well. so you may need to check some other place,Here are my suggestions.

  1. clean project
  2. check multi-language files
  3. or just use String.format just like others said



回答2:


Set parameter formatted to true in resources:

<string name="some_text" formatted="true">
    Use for String.format method. Parameter one: %s1
</string>

and use this way:

String.format(context.getString(R.string.some_text,"value 1"))

or this way:

context.getString(R.string.some_text,"value 1"))

Note:formatted flag should be set to true only for strings with placeholders




回答3:


Try File -> Invalidate Caches / Restart..., it fixed the problem for me.




回答4:


For the sake of others who might find this thread, one possible cause of this warning is that you have multiple languages defined in string resource files and you did not specify format arguments in one or more of them.

For example, if you have a strings.xml in your values folder, and another strings.xml in your values-es folder, but you only added format arguments to the strings.xml in your values folder, then the warning will be triggered because of the lack of format arguments in the string resource of strings.xml in your values-es folder.




回答5:


Try doing a 'clean project' followed by a close and reopen of Android Studio.

That fixed it for me, it looks like some minor Android Studio /Lint bug.




回答6:


You need String formatter. Please change below code from

 getResources().getString(R.string.create_group_select_people, countMax);

to

String temp =  String.format(getResources().getString(R.string.create_group_select_people), countMax);

For more detail information refer




回答7:


You're probably missing the format method of the String class, If you're setting it in a TextView, the proper way is:

textView.setText(String.format(getResources().getString(R.string.create_group_select_people), countMax));



回答8:


Make a function and put your code inside it and add this @SuppressLint("StringFormatInvalid") just before the function. Hope it helps.



来源:https://stackoverflow.com/questions/40765890/format-string-xxx-is-not-a-valid-format-string-so-it-should-not-be-passed-to-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!