Advertisement
Android SDK

Android SDK Quick Tip: Formatting Resource Strings

by

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>>!"
and
"<< 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);
Android SDK Format String Output

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.

Conclusion

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 androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Related Posts
  • Code
    Mobile Development
    Streaming Video in Android Apps54dpm preview image@2x
    The Android platform provides libraries you can use to stream media files, such as remote videos, presenting them for playback in your apps. In this tutorial, I will show you how to stream a video file using these libraries.Read More…
  • Code
    Android SDK
    Using New Relic to Monitor Your Android AppGetting started new relic retina preview2
    In the last two years, New Relic has focused hard on building out a solution for monitoring the performance of mobile apps. In this tutorial, we will look at how you can start using New Relic to monitor the performance of an Android application.Read More…
  • Code
    Android SDK
    Create a Music Player on Android: Project Setup0d63m preview image@2x
    The Android platform provides resources for handling media playback, which your apps can use to create an interface between the user and their music files. In this tutorial series, we will create a basic music player application for Android. The app will present a list of songs on the user device, so that the user can select songs to play. The app will also present controls for interacting with playback and will continue playing when the user moves away from the app, with a notification displayed while playback elapses.Read More…
  • Code
    Android SDK
    Using the Accelerometer on Android06lom preview image@2x
    In this tutorial, we are going to explore how to use the accelerometer, one of the many hardware sensors of modern smartphones, in an Android application. I'll explain what an accelerometer is and why it may be something you want to take advantage of in your Android applications.Read More…
  • Code
    Android SDK
    Android SDK: Next StepsAndroid preview@2x
    In this series, we've begun learning how to develop Android applications from scratch. We started exploring the development tools, got acquainted with the basic elements in an application project, looked at user interface design, interactivity, resources, and data, and we've also took a closer look at what happens when your application is running. What we've covered so far should put you in a good position to get started creating functional Android applications, but Android has a lot more to offer so the range of possibilities is virtually endless. You may therefore struggle to choose what to learn next. In this part, we'll wrap up the series by pointing out some possible directions for future learning. After this, the final part will be a quiz on what we covered throughout the series.Read More…
  • Code
    Android SDK
    Android SDK: User Interface DesignAndroid preview@2x
    In this series we're learning about Android SDK development from scratch! In this tutorial, we will build a simple user interface layout with a few visual elements.Read More…