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.
  • Pingback: Tweets that mention Developing an android twitter client using twitter4j | Enbake Consulting -- Topsy.com

  • Farhanahmad123

    Its a nice tutorial… will be more helpfull if you attach the whole project since this post is intended to new users as you are trying to make an application from scratch….

    thanx,

    • http://twitter.com/enbake Enbake Consulting

      Added the sample project. Thanks for the feedback !!

  • Farhanahmad123

    Its a nice tutorial… will be more helpfull if you attach the whole project since this post is intended to new users as you are trying to make an application from scratch….

    thanx,

    • Anonymous

      Added the sample project. Thanks for the feedback !!

    • Dark Musician

      Where is the link? I can’t see it!

  • http://twitter.com/enbake Enbake Consulting

    Please note that the sample project contains the eclipse workspace and required android API runlevel 9 to run !!

  • Anonymous

    Please note that the sample project contains the eclipse workspace and required android API runlevel 9 to run !!

  • Sean

    Thank you very much! It is a good tutorial.
    But how to logout?
    At the first time when I connect, it is ok, but I want to sign in with another account, but the twitter web site do not show. And it always sign in with the first account.
    How to sign in with different account?

    • Tester1

      Same problem here, how do I log out?!

  • Sean

    Thank you very much! It is a good tutorial.
    But how to logout?
    At the first time when I connect, it is ok, but I want to sign in with another account, but the twitter web site do not show. And it always sign in with the first account.
    How to sign in with different account?

    • Tester1

      Same problem here, how do I log out?!

  • Marcelo Duende

    Thank you, amazing tutorial.

    I got one problem, is it normal the app restart the initial Activity after the login? It is happening here, kind weird.

    Thanks dude.

    • Marcelo Duende

      Nevermind, the Android manifest was wrong :)

  • Marcelo Duende

    Thank you, amazing tutorial.

    I got one problem, is it normal the app restart the initial Activity after the login? It is happening here, kind weird.

    Thanks dude.

    • Marcelo Duende

      Nevermind, the Android manifest was wrong :)

  • Adry Ma

    It doesn’t run :

    The method getOAuthAuthorizedInstance(String, String, AccessToken) is undefined for the type TwitterFactory

  • Adry Ma

    It doesn’t run :

    The method getOAuthAuthorizedInstance(String, String, AccessToken) is undefined for the type TwitterFactory

    • Abhinav Mehrotra

      Did you find any solution for this?

  • Marcio Andrey Oliveira

    Hi. I replaced constants OAUTH_CONSUMER and OAUTH_SECRET with consumer and secret keys I got on twitter site.

    The problem is that after the code uri = getIntent().getData(); uri is null and that generates a null pointer exception in the line AccessToken at = tt.getOAuthAccessToken(rToken, oauthVerifier);

    Do you have any clue?

    Regards.

  • Marcio Andrey Oliveira

    Hi. I replaced constants OAUTH_CONSUMER and OAUTH_SECRET with consumer and secret keys I got on twitter site.

    The problem is that after the code uri = getIntent().getData(); uri is null and that generates a null pointer exception in the line AccessToken at = tt.getOAuthAccessToken(rToken, oauthVerifier);

    Do you have any clue?

    Regards.

  • http://www.facebook.com/mahbub.rahman.906 Mahbub Rahman

    In my case, I am running the code in emulator and Force Close Error is coming. How I can solve it? Please help.

  • Anonymous

    I tried running this, but this line 41 throws a “NetworkOnMainThreadException”:

    rToken = twitter.getOAuthRequestToken(callbackURL);Do you have an update example that does this request in the background?

    • Anonymous

      Answered my own question by putting this call in a background thread.

    • Abhinav Mehrotra

      Try it on AsyncTask or Thread, it will work.
      You cannot do Network Request on main thread.

  • http://www.facebook.com/profile.php?id=100002065325647 Mohammad Hosam

    Unable to resolve target ‘android-9′ ???

  • Khang Hieuthuan

    very good, thanks admin !

  • redsatyr

    Thank you! really helpful to me~

  • Parth Vora

    I have problems as well its not working for me…pls help…