Spring Android: Bringing Spring Components to Your Android Apps

by Chris King

Spring Android helps unify the worlds of enterprise and Android development, offering a simple framework for accessing RESTful resources.

Android has grown rapidly in recent years, increasingly challenging the iPhone in units sold and apps available. One major reason for the strong app presence on Android is its Java programming API, which allows the large number of Java developers to bring their existing skills from the server or the desktop to the mobile device.

However, bringing over your skills and bringing over your code are two different things. Most applications written today, particularly on enterprise servers, use popular frameworks that run on Java but are not included in the core Java language. If you wish to bring such an app to Android, you will need to replace all your app's calls to the framework, which could take as long as simply rewriting the app from scratch.

Help is on the way. SpringSource, a company that supports Spring and several other popular open-source projects, has recently announced the creation of Spring Android. This is not a complete reimplementation of Spring, but rather a port of some of the most useful client-side components of Spring to Android. Their initial release includes a port of commons logging, which is internally used by a wide variety of projects, as well as RestTemplate, which significantly eases the development of RESTful client applications.

This article will show how you can add Spring Android to your app, and walk through an example of using it to quickly build a Twitter client.


Visit the Android Dev Center


Things You'll Need

The Spring Framework and REST

Spring has become one of the most popular Java frameworks, offering a variety of useful services for applications. While it can be used on many platforms, it has gained its greatest popularity on enterprise servers, where it offers useful, intuitive, and scalable mechanisms for managing data and handling client interactions. Spring contains a number of modules, including several aimed primarily at client applications. One of Spring's strengths is its ability to abstract away the complexity of network interactions and provide a more programmatic way to communicate.

Representational State Transfer, or REST, is a type of software architecture that uses verbs and nouns to govern all client-server interactions. Based on HTTP, it supports commands to add data (via PUT), view data (via GET), modify data (via POST), and so on. Each URI represents a conceptual noun, so a command to GET http://example.com/cake.dat refers to the same entity that you would remove with a command to DELETE http://example.com/cake.dat. Because REST does not rely on the server maintaining the client's state, it tends to be much simpler and more scalable than other Web architectures.

The key piece that Spring Framework offers to support RESTful clients is RestTemplate. This class supports generating URIs at runtime that refer to REST resources. It also provides a pluggable framework for translating the server's responses from raw HTTP into a form usable by your application. Out of the box it can translate basic string and binary responses; with popular third-party plug-ins it can parse standard response types such as JSON; and, with a bit of work, you can write your own custom converter to handle your server's responses. For this example we'll be using the Jackson library to parse JSON responses from Twitter; however, if you already have your own RestTemplate-based app, you can use your own message converter instead.

Adding Spring Android to Your Project

If you don't already have a working Android environment on your box, follow the links above to install recent versions of Eclipse, Android, and the Plug-in. Spring Android should work on all recent versions of the Android SDK; this article was written using version 2.2. You should also download the JAR files for Spring Android and Jackson.

Once your Android environment is working properly, create a new Android project called Springy. Figure 1 shows the options you can place in the wizard to create your skeleton project.

Creating a New Android Project in Eclipse
Figure 1. Creating a New Android Project in Eclipse

Since we'll be accessing the Internet to retrieve Twitter data, open AndroidManifest.xml and add a uses-permission directive for android.permission.INTERNET, as Figure 2 shows.

Adding Internet Permission to the Android Manifest
Figure 2. Adding Internet Permission to the Android Manifest

You'll also want to make a slight edit to the auto-generated file in /res/layout/main.xml. Add the android:id attribute to the TextView.


This will allow us to reference the text view from within our app.

Figure 3 shows how to add the necessary JAR files to your project's Java build path. Do not add the commons logging JAR; it will automatically be included as needed. We're including the Jackson jars here so Spring Android can automatically parse JSON responses from Twitter. If you have your own message converters, you can add the appropriate JARs here or import those .java files into your code.

Adding Spring and Jackson JAR Files to the Android Project
Figure 3. Adding Spring and Jackson JAR Files to the Android Project

Invoking Twitter's APIs

All of our work will be done in Springy.java. We'll modify onCreate to start a thread that pulls data from Twitter.

public class Springy extends Activity {

   public void onCreate(Bundle savedInstanceState) {

Within this thread, we'll set up our query. RestTemplate offers a very useful and powerful substitution system. In our example we will look for the three most recent tweets using the #nomnomnom hashtag, in hopes of finding something delicious to eat.

private Thread getUpdates = new Thread() {
 public void run() {
   String display = "";
   try {
     RestTemplate restTemplate = new RestTemplate();
     String query = "nomnomnom";
     int count = 3;
     String url = "http://search.twitter.com/search.json" +
       "?q=#{query}&p=1&rpp={count}" +

Incredibly, invoking the REST API and unmarshalling the server response requires only a single line of code.

HashMap response = restTemplate.getForObject(url, HashMap.class, query, count);

RestTemplate provides a pluggable system of message converters that lets you convert any content type from the server into any type of Java object. In your own apps, you might invest the time to write your own custom converter. For this sample, we'll take the default untyped HashMap returned by Jackson and look through it, building up a view of the returned results.

   ArrayList results = (ArrayList) response
   for (HashMap tweets : results) {
       String tweet = (String) tweets.get("text");
       String author = (String) tweets.get("from_user");
       display += "@" + author + ": " + tweet + "n";
} catch (Exception e) {
   display = e.getMessage();

Finally, we'll update the Android UI to show the latest tweets. We'll use a special Android method to perform the update on the UI thread; this protects access to UI elements.

final String toShow = display;
           runOnUiThread(new Runnable() {
               public void run() {
                   ((TextView) findViewById(R.id.text)).

And that's it! By building on top of the work previously done by others, you've rapidly built an Android application that interacts with Twitter.

Running Your App

If you have an Android device, you can attach it to your development machine via a USB cable; otherwise, Eclipse will use your installed emulator. Select Run As > Android Application to load and launch the application; if you'd like to step through and see what it's doing, use Debug As > Android Application. When the app starts, you'll first see the standard "Hello World, Springy!!" message. Behind the scenes, it will start your thread and execute the search. After it finishes parsing the response, you'll see the screen automatically update with the tweets it found, looking like Figure 4.

Displaying Twitter Results Obtained from RestTemplate
Figure 4. Displaying Twitter Results Obtained from RestTemplate.

Springing Forward

Of course, there are many modifications you could make to this sample app to create a more compelling client: accept user input for queries, or follow links to other hashtags, or support retweeting. The Spring Android framework can handle all of these REST API calls, and your app can handle any of the responses.

Spring Android should provide a significant boost to existing Spring developers out there, who will be able to bring over their tried-and-tested client code to Android. You can keep on invoking your great REST APIs without needing to deal with the details of HTTP traffic, and you can serialize to and from appropriate Java objects.

Additionally, veteran Android developers may be interested in checking out Spring Android. It doesn't provide anything that basic Android does not, but it does let you accomplish it with far less code and error-handling required. You can abstract away most of your network logic and focus on the semantics of your operations. The next time you're writing an Android app that's accessing a RESTful server, consider investigating Spring Android.

Download the Code

About the Author

Chris King is a senior software engineer at Gravity Mobile. He is the author of Advanced BlackBerry Development and Advanced BlackBerry 6 Development and a co-author of Android in Action, Second Edition. When he isn't programming or writing for fun or profit, Chris can be found reading, baking, cycling, or hiking throughout the San Francisco Bay Area.

This article was originally published on Wednesday Feb 2nd 2011
Mobile Site | Full Site