This blog will talk about how to use the Twitter4J library to login in via twitter and get user details. Twitter4j libraries needed for this demo, can be downloaded from the following link:Twitter4jLibs

1. Create an app in twitter by vising
2. Note down the consumer key and secret

Steps for configuring Twitter4j:
1. Create a utils class and place the following method in it, I use the CommonUtilities file.

public static Twitter getTwitterInstance() {
    // for twiiter login
    ConfigurationBuilder builder = new ConfigurationBuilder();
    Configuration configuration =;
    TwitterFactory factory = new TwitterFactory(configuration);
    Twitter twitter = factory.getInstance();
    return twitter;

Global is a class that holds all the constants. I will mention the other constants needed below as we need them.

Create an instance of the twitter object and in an AsyncTask make a network call.

mTwitter = CommonUtilities.getTwitterInstance();
new TwitterLoginAsyncTask(mListener,mTwitter).execute();

mListener is an object of an interface that your calling class will be implementing, the calling class can be an activity or a fragment. And its definition would be:

public interface ResponseListener {
    public void onResponseListener(Object object);

The AsyncTask looks as under:

public class TwitterLoginAsyncTask extends AsyncTask<Void, Void, RequestToken>{
    private ResponseListener mListener;
    private Twitter mTwitter;
    public TwitterLoginAsyncTask(ResponseListener listener, Twitter twitter) {
        mListener = listener;
        mTwitter = twitter;

    protected RequestToken doInBackground(Void... params) {
        try {
            RequestToken requestToken = mTwitter
            return requestToken;
        } catch (TwitterException e) {
        return null;
    protected void onPostExecute(RequestToken result) {
        if(mListener != null) {

The twitter callback URL can be anything you give on the developer twitter console, but in the application it would be something like oauth://app_name.

You need to define the same in the manifest file as under:

<activity android:name="com.example.appname.activities.LoginActivity"
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="oauth" android:host="app_name"/>

The other constants that might be needed later on are: (declare them in a constants file)

public static final String URL_TWITTER_AUTH = "auth_url";
public static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
public static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

Store the request token which you receive in the onResponseReceived method in the calling class, as that would be needed to login

Your onResponseReceived method should look like this:

public void onResponseReceived(Object object) {
    if(object != null) {
        if(object instanceof RequestToken) {
            mRequestToken = (RequestToken)object;
            * Loading twitter login page on webview for authorization
            * Once authorized, results are received at onActivityResult
            final Intent intent = new Intent(getAppContext(), 
            startActivityForResult(intent, TWITTER_SIGN_IN);

The calling activity must have the onActivityResult method, and that would look like this:

public void onActivityResult(int requestCode, 
                   int responseCode, Intent intent) {
    if(requestCode == TWITTER_SIGN_IN) {
        if (responseCode == Activity.RESULT_OK) {
            // handle twitters response
            if(intent.getExtras() != null) {
                String verifier = intent.getExtras()
                if (verifier != null) {
                    // oAuth verifier
                    try {
                        // Get the access token
                        new TwitterGetOauthAccessToken(mRequestToken, 
                                  verifier,mTwitter, mListener).execute();
                     } catch (Exception e) {
                        // Check log for login errors
                        Log.e("Twitter Login Error", "> " + e.getMessage());

Your TwitterGetOauthAccessToken async task should look like this:

public class TwitterGetOauthAccessToken extends AsyncTask{
    private RequestToken mRequestToken;
    private String mVerifier;
    private Twitter mTwitter;
    public TwitterGetOauthAccessToken(RequestToken requestToken ,
               String verifier, Twitter twitter) {
        mRequestToken = requestToken;
        mVerifier = verifier;
        mTwitter = twitter;
    protected TwitterResponse doInBackground(Void... params) {
        TwitterResponse twitterResponse = new TwitterResponse();
        try {
            AccessToken accessToken = 
                  mTwitter.getOAuthAccessToken(mRequestToken, mVerifier);
            Log.v("TAG", "twitter access token >> " + accessToken.getToken());
            Log.v("TAG ", "twitter oauth secret >> " + 
            try {
                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                // this is where you get the profile information
                User user = mTwitter.showUser(userID);
                String username = user.getName();
                Log.v("TAG ", "twitter username >> " + username);
             }catch(TwitterException e) {
         } catch (TwitterException e) {
       return twitterResponse;
    protected void onPostExecute(TwitterResponse result) {

We use AsyncTasks to prevent the NetworkOnMainThread exceptions