How to Talk to the Twitter Server with Your Android App

By Barry Burd

If you want to make a Twitter app that functions with an Android device, you need to have your device talk to the Twitter server. The following example contains a fake snippet of code from the main activity in an Android app.

Twitter twitter;
// … Some code goes here
ConfigurationBuilder builder =
new ConfigurationBuilder();
builder
.setOAuthConsumerKey(“01qedaqsdtdemrVJIkU1dg”)
.setOAuthConsumerSecret(“TudeMgXgh37Ivq173SNWnRIhI”)
.setOAuthAccessToken(“1385541-ueSEFeFgJ8vUpfy6LBv6”)
.setOAuthAccessTokenSecret(“G2FXeXYLSHI7XlVdMsS2e”);
TwitterFactory factory =
new TwitterFactory(builder.build());
twitter = factory.getInstance();

This code creates an instance of the Twitter class.

Here’s some information regarding the Twitter4J API:

  • A Twitter object is a gateway to the Twitter servers.

    A call to one of the methods belonging to a Twitter object can post a brand-new tweet, get another Twitter user’s timeline, create favorites, create friendships, create blocks, search for users, and do other cool things.

  • TwitterFactory is a class that helps you create a new Twitter object.

    As the name suggests, TwitterFactory is a factory class. In Java, a factory class is a class that can call a constructor on your behalf.

  • Calling the getInstance method creates a new Twitter object.

    A factory method, such as getInstance, contains the actual constructor call.

The ConfigurationBuilder, TwitterFactory, and Twitter classes belong to the Twitter4J API. If, instead of using Twitter4J, you use a different API to communicate with Twitter servers, you’ll use different class names. What’s more, those classes probably won’t match up, one for one, with the Twitter4J classes.