Integrating Twitter Into Your Android App

March 7, 2012

Foreword

Consider that you might want to just actually use the real Twitter instead of reinventing the wheel. That said, sometimes it can be useful to get assets from Twitter.com to display in your app, as they pertain to your app.

In Android, you can launch Twitter with one line of Code:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.twitter.com"));

You can also share content with about just as many lines, by using an ACTION_SEND. Anyway, if you need to do something deeper, you have to leverage the Twitter API directly.

Get the Twitter4J Jar

Download this: http://twitter4j.org/en/twitter4j-android-2.2.5.zip. Extract the core jar, and put it in the libs directory of your android project.

Register Your App with Twitter

You need to do this to placate their OAuth nonsense. Visit https://dev.twitter.com/apps/new.

Add the OAuth Keys to Your App

In res/values/strings.xml, add the lines:

<string name="twitter_oauth_key">PUT YOUR CONSUMER KEY HERE</string>
<string name="twitter_oauth_secret">PUT YOUR CONSUMER SECRET HERE</string>

Note: Here we take a No-BS approach to the OAuth stuff. (In figuring out how to do this, there are a lot of posts on the internet you have to sort through that don’t.) One solution for hiding your OAuth secret is to keep it on a server and proxy your requests to Twitter through that host. Needless to say, that’s not covered here.

Get a Handle to the Twitter obejct in Java

ConfigurationBuilder cb = new ConfigurationBuilder();
String key = getApplicationContext().getString(R.string.twitter_oauth_key);
String secret = getApplicationContext().getString(R.string.twitter_oauth_secret);
cb.setOAuthConsumerKey(key); 
cb.setOAuthConsumerSecret(secret);
Twitter twitter = TwitterFactory(cb.build()).getInstance();

Example Use

And that’s basically it. Now you you can get info from twitter using the Twitter object. For example, here’s how to get a list of tweets about Potatos.

List<Tweet> tweets = twitter.search(new Query("Potatos")).getTweets();

See Code in an Example App

I have created an example app that shows the above. Check it out on Github: https://github.com/jamesonwilliams/AndroidTwitterExample

References

  1. Stack Overflow – Android Twitter xAuth example using twitter4j
  2. Twitter4J Twitter Class Documentation
  3. Twitter4J Example Code
  4. Twitter Endorsed Client Libraries

2 Responses to “Integrating Twitter Into Your Android App”

  1. lana says:

    good tutorial, works fine , thanks .
    please can you provide us a method of posting a tweet through my app? using Oauth .

  2. Igor G. says:

    Your code does not provide an example of how to post tweets (using a webview). That is what most developers are interested in anyway.

Leave a Reply