August 23, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Using Spring Android to Build a Twitter client, Page 2

  • February 2, 2011
  • By Chris King
  • Send Email »
  • More Articles »

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 {

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       getUpdates.start();
   }

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}" +
       "&result_type=recent&lang=en";

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
       .get("results");
   for (HashMap tweets : results) {
       String tweet = (String) tweets.get("text");
       String author = (String) tweets.get("from_user");
       display += "@" + author + ": " + tweet + "n";
   }
} catch (Exception e) {
   e.printStackTrace();
   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)).
                       setText(toShow);
               }
           });
       }
   };
}

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.


Tags: Spring, Android

Originally published on http://www.developer.com.

Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel