Accessing Twitter API 1.1 on Android

This tutorial covers the basics of using the Twitter API to access your own tweets, most likely with a view to displaying them in an app. Updated on Friday 13th September 2013, source code available on Github

Twitter API v1.0

On the 5th March, 2013, v1 of the Twitter API will be no longer be accessible. Currently, you can get access to Twitter REST API using unauthenticated HTTP requests. For example, the following url will provide you with the JSON of my last 10 tweets:
http://api.twitter.com/1/statuses/user_timeline.json?count=10&screen_name=%20Linnesq
If you still want to learn how to make a HTTP request and process JSON responses on Android, I suggest looking at this tutorial on Vogella’s site.

Twitter API v1.1

The most pertinent aspect of using the v1.1 API to this blog post is that all requests must be authenticated using OAuth 1.0a. You can find out more about what is new in this API here.

Single User OAuth – getting access tokens

When I first looked at implementing OAuth in order to access my tweets and display them in an app, I thought it seemed like a steep learning curve. However, it is actually quite simple with the help of some really useful libraries. To start off, you will need to log in to https://dev.twitter.com/apps and create an application – this will provide you with the following keys – consumer key, consumer secret, (and by clicking on the ‘Create my access token’ button) access token and access token secret.

Twitter API ME

To copy and paste from Twitter’s own page, “Twitter API ME is a Java library for interacting with Twitter using OAuth.” You can download version 1.8 here, and view code examples here. Please use version 1.9 instead, available here.
Once you have zip downloaded, copy the twitter_api_me-1.8.3.jar to your Android project’s ‘libs’ folder. Instead use the 1.9 android version and add twitter_api_me-1.9.jar and json-me.jar to the class path
libs

and make sure to include it in the build path by clicking ‘add jar…’ and selecting the above jar. Once you have done this you should see something like this…
build_path

Now you have your access tokens and a way to interact with the Twitter API that does all the OAuth for you!

Using Twitter API ME

As you might expect, getting data from Twitter involves making network calls that could take some time. We should wrap our request to Twitter in a sub-class of AsyncTask. The following gist gives an example of how I would go about getting the text part of my last 20 tweets (by using my access tokens, the user of the app never needs to authenticate by logging in to Twitter to start accessing my tweets). If you have any questions please feel free to leave a comment below.