This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.
This quick tip shows you how to create and use string resources as format strings. You will achieve this by creating and configuring the appropriate string resources in XML and using them programmatically to supply the various typed parameters.
Step 0: Getting Started
Begin by creating an Android project. If you’d like to just follow along, you can find a sample project with code for formatting strings.
Step 1: Creating the String Resources
String resources are often stored within the /res/values/strings.xml file of the resource hierarchy. Any strings you add to the strings.xml file will be accessible within your application. The following is a sample strings.xml file:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Format Strings</string> <string name="hello">Yo!</string> </resources>
This string resource file defines two strings. One for the application name and another called hello. Remember that if your string resource has complex character codes, you may need to quote the entire string. You can add format string resources much as you do regular string resources.
Step 2: Why Use Format Strings?
Format strings are a convenient way to build up one string that has variable content. This is best illustrated by example. In homage to the popular video game Oregon Trail, let’s look at an infamous message players inevitably saw while dragging their family across the Midwest:
"You shot <<insert number>> pounds of meat!"
The number of pounds of game meat changes based upon how the player shoots. There are a number of ways (both good and bad) that developers might approach this problem. A developer might:
- Avoid the problem entirely and create a generic string, shying away from the specifics: "You shot something!"
- Create two string resources (e.g. "You shot " and " pounds of meat!") and sandwich them together around a number programmatically.
- Brew their own solution, doing some black magic with string search and replace methods (e.g. "You shot ##PUT_NUM## pounds of meat!" and the String replace() method).
- Ask themselves if format strings work in Android resource files and read this tutorial.
We didn’t make these approaches up. We’ve seen them all. Only two of these approaches are reasonable: the first and the last.
Sometimes, coming up with a generic string is the right answer—it’s simple and straightforward. Generally, this is the best approach when the information being relayed can be made generic without the application losing something. Other times, you need to communicate important and specific information to the user. In Oregon Trail, if you shot 2 pounds of meat, then you’d keep hunting (or starve), whereas, if you shot 1234 pounds of game, your wagon was maxed out anyway, so you’d likely choose to mosey along down the trail (with a full belly).
You might ask why the sandwich approach isn’t so great. First, using two strings clutters your resource files and makes them difficult to maintain. Secondly, when you go to internationalize your application, you may find that those two strings are no longer appropriate—it can get very complex if your string has more than one parameter, too. Brewing your own solution means introducing more code to maintain and assuming that you can do string manipulation better than the stock Java libraries can.
Better to use the standard methods for formatting strings and create a single string resource with parameters.
Step 3: Creating Format Strings
Format strings can have one parameter or many. Each parameter is numbered and typed. The parameter number is specified using % followed by the number of the parameter, which corresponds to the order in which the parameter values will be supplied programmatically. For example, the first parameter would be %1, the second %2, etc. The second item each parameter has is a type (think C-style printf()), specified by a $ and a letter specifying that type.
For example, a string would be $s; a number might be $d. Therefore, our string resource could be crafted as:
<string name="meatShootingMessage">You shot %1$d pounds of meat!</string>
Step 4: Supplying Format Strings with Numeric Parameters
Now that you’ve created a proper format string, you can load it, format it, and display it to users. The following code loads the string resource, supplies the single numeric parameter and generates the completed string:
int numPoundsMeat = 123; String strMeatFormat = getResources().getString(R.string.meatShootingMessage); String strMeatMsg = String.format(strMeatFormat, numPoundsMeat);
Step 5: Supplying Format Strings with Multiple Parameters
Let’s try another example. This time we’ll create two more format string resources, each with two parameters. In Oregon Trail, the player’s family often got sick and sometimes died. The two messages players often saw went something like this:
"<<name of character>> has << name of disease or trauma>>!"
"<< name of disease or trauma>> has killed <<name of character>>!"
Creating the two format string resources is fairly straightforward:
<string name="diseaseMessage">%1$s has %2$s!</string> <string name="diseaseMessage2">%1$s has killed %2$s!</string>
The following code loads the string resources, supplies the parameters, and generates the completed strings:
String name = "Sally"; String disease = "Typhoid"; String strDisease1Format = getResources().getString(R.string.diseaseMessage); String strDisease1Msg = String.format(strDisease1Format, name, disease); String strDisease2Format = getResources().getString(R.string.diseaseMessage2); String strDisease2Msg = String.format(strDisease2Format, disease, name);
Bonus: Format String Parameter Order is Flexible and Locale-Friendly
You may have noticed in the last step that the parameters were swapped in the second string (strDisease2Msg). This is a little annoying, no? Luckily, there’s absolutely no reason format string contents must dictate the order of the parameters. Instead, simply number the parameters in the format string resource in the order that you want to supply them. For example, if you always want to supply the character name, followed by the disease name, then define your format string like this:
<string name="diseaseMessage2">%2$s has killed %1$s!</string>
Therefore, your code would then look like this:
String strDisease2Msg = String.format(strDisease2Format, name, disease);
That makes it much easier on the developer. Also, in terms of string translation, many of the string parameters get jumbled up in different languages anyway.
In this quick tip you learned how to use format strings as Android string resources. Format strings allow for flexible and maintainable application assets.
About the Authors
Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to firstname.lastname@example.org, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.