Issue
I define a String in my strings.xml file:
<string name="unformatted_string">Here\'s a song I\'ve created just for you\! {0}</string>
And then I fetch that string and using MessageFormat.format, I replace {0} with a URL:
String str = MessageFormat.format(getString(R.string.unformatted_string), url);
When I print str, I see this:
Heres a song Ive created just for you http://www.google.com
The MessageFormat documentation states that rules for quotes are somewhat confusing, and then goes on to provide only a single example that only uses double-quotes. From my reading of the documentation, it seems my single-quote woes could be solved by using ''':
<string name="unformatted_string">Here'''s a song I'''ve created just for you\! {0}</string>
But the Android Resource Packaging step throws an error because I have an apostrophe not preceded by a \
.
My only requirement is that the string be defined in strings.xml (to support localization).
Solution
The file is an android resoure file, which mandates that every apostrophe is escaped with a preceding backslah. And MessageFormat requires every apostrophe in the pattern to be doubled. So you need two escaped apostrophes:
<string name="unformatted_string">Here\'\'s a song I\'\'ve created just for you\! {0}</string>
Answered By - JB Nizet
Answer Checked By - Katrina (JavaFixing Volunteer)