Developing an android twitter client using twitter4j

Recently, we worked out an android twitter client for one for our esteemed clients. In this blog, I will try to explain on how to go about on building such an android application from scratch.
  1. Register your application on http://dev.twitter.com/apps/new.
  2. Please ensure that the application is of the browser type. Please fill anything in the callback url like http://twitter-test.com
  3. You will get the consumer key and the consumer secret once the application registration has been successful.
  4. Create an android project in eclipse(We use eclipse mostly, Please adjust the eclipse specific notes in this blog to adjust to your editor).
  5. Import twitter4j(http://twitter4j.org/en/index.html) as an external jar. This seems to be one of very few complete twitter libraries for java.
  6. We will try to post a status update to twitter. Lets get down to a bit of coding now. Place the following code where you want to trigger the twitter authentication process.
  7. 	Twitter twitter = new TwitterFactory().getInstance();
    	try
    	{
    
    	twitter.setOAuthConsumer(<consumer_key>, <consumer_secret>);
    	String callbackURL = "twitter-client:///";
    	rToken = twitter.getOAuthRequestToken(callbackURL);
    	startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rToken.getAuthenticationURL())));
    	}
    	catch(IllegalStateException e)
    	{
    	// access token is already available, or consumer key/secret is not set.
    	if(!twitter.getAuthorization().isEnabled()){
    	System.out.println("OAuth consumer key/secret is not set.");
    	System.exit(-1);
    	}
    	}
    	catch(Exception e)
    	{
    	Toast.makeText(TwitterClient.this, "Network Host not responding",Toast.LENGTH_SHORT).show();
    	}
    	
  8. Lets try to deciper the code here
  9. First we get the instance of the twitter factory and the set the oAuth consumer and secret with the keys that we got from the twitter site.
  10. Next we point the callbackURL to the intent filter that we would create in the application xml file. The intent filter is required so that the application catches the intent when the browser redirects back after successful twitter authentication. In my case i have added the following intent filter to my AndroidManifest.xml
  11. <intent-filter>
    <action android:name=”android.intent.action.VIEW” />
    <category android:name=”android.intent.category.DEFAULT” />
    <category android:name=”android.intent.category.BROWSABLE” />
    <data android:scheme=”twitter-client”/>
    </intent-filter>
    You can read more about intent filters on the android sdk site.
  12. Next we get the oauth request token and start the activity which will get the username/password and give authorization to our twitter application.
  13. When we return back from twitter, will place the following code on onResume activity callback:
    </li>
    @Override
    
    public void onResume() {
    
    super.onResume();
    
    Uri uri = getIntent().getData();
    
    if (uri != null) {
    
    oauthVerifier = uri.getQueryParameter("oauth_verifier");
    
    }
    
    try {
    
    Twitter tt = new TwitterFactory ().getInstance();
    tt.setOAuthConsumer(<consumer_key>, <consumer_secret>);
    AccessToken at = tt.getOAuthAccessToken(rToken, oauthVerifier);
    String token = at.getToken();
    String secret = at.getTokenSecret();
    // Post to twitter.
    Twitter t = new TwitterFactory().getOAuthAuthorizedInstance(<consumer_key>,
    <consumer_secret>,
    new AccessToken (token, secret));
    t.updateStatus("Test Android Twitter Client");
    
    } catch(Exception e) {
    Toast.makeText(TwitterClient.this, "Network Host not responding",Toast.LENGTH_SHORT).show();
    }
    }
    
  14. Twitter has sent the verifier in the parameter of the return url, so we get it using getIntent().getData().getQueryParameter(“oauth_verifier”)
  15. Now when we have the verifier, we can get the access token and call the twitter4j method to update the status on twitter. twitter4j supports most of the twitter API and can be used for any operation which can be performed using twitter API.
Hope this helps someone. In case you have any queries, Please feel free to leave them in comments. We will be more than happy to help !! Edit: Here is the link to Sample Application. Please replace the variables OAUTH_CONSUMER and OAUTH_SECRET with the consumer and secret keys of the application that you have registered with twitter.