Sunday 3 March 2013

Android Twitter integration. twitter4j How to logout from twitter4j

After working with twitter4j for a while I came to a point where user needs to logout from twitter account and let another user to login. Searching google doesn't seem to help a lot as there is no best solution out there I supposed. So I have created a work around for it and it seems to work reasonably well.

1. Some important parameter that needs to append to the url
Accroding to the twitter API reference:

force_login and screen_name are the 2 parameters that can be added to the OAuth token request. This means when user opens the webview in Android application, it will display the login page with username blank if you set the screen_name equals to empty. This is important as when you switch the user account you don't really want the next user to see the previous user's name.

2. Cancel the twitter login webview(logout)
Sometimes user wants to click cancel (as back button) on webview , but the Twitter instance has already be instantiated and if you re-use it it will throw exception saying Access token already exists(as I can remembner :)), to resolve this apply the following code into you activity's onActivityResult method:




  
if(resultCode == Activity.RESULT_CANCELED){
mTwitter.shutdown();
  mTwitter = new TwitterFactory().getInstance();
  mTwitter.setOAuthConsumer(getResources().getString(R.string.twitter_consumer_key),
    (getResources().getString(R.string.twitter_consumer_secret)));
}
By doing this, the twitter instance will be reset and ready for next user to user it.


To log out the user simply call the following method:

mTwitter.setOAuthAccessToken(null);
mTwitter.shutdown();
These may not be the best solution so far as I know, but at least it does the trick, please drop me a line if you find anything better or. Thanks!

6 comments:

  1. mTwitter.setOAuthAccessToken(null);
    mTwitter.shutdown();

    These functions donot work.I still see the earlier user's name. Also if force_login = true has to be used,where can I use them in browser as my app shows twitter login through browser. Please help!!

    ReplyDelete
  2. But what is mTwitter ? is this a Twitter object?
    Reply me on babulpatel1309@gmail.com

    ReplyDelete
    Replies
    1. Hi Babul

      It is an object from twitter4j library found here http://twitter4j.org/en/index.html

      Cheers

      Delete
  3. how to make an android app to login from twitter and fetch user info after that make logout in android

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. shutdown() not found how to resolve

    ReplyDelete