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

Pre-requisites:
1. Create an app in twitter by vising https://apps.twitter.com
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();
    builder.setOAuthConsumerKey(Global.TWITTER_CONSUMER_KEY);
    builder.setOAuthConsumerSecret(Global.TWITTER_CONSUMER_SECRET);
    Configuration configuration = builder.build();
    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;
    }

    @Override
    protected RequestToken doInBackground(Void... params) {
        try {
            RequestToken requestToken = mTwitter
                 .getOAuthRequestToken(Global.TWITTER_CALLBACK_URL);
            return requestToken;
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(RequestToken result) {
        super.onPostExecute(result);
        if(mListener != null) {
            mListener.onResponseReceived(result);
        }
    }
}

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"
    android:screenOrientation="portrait">
    <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="oauth" android:host="app_name"/>
    </intent-filter>
</activity>

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:

@Override
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(), 
                           WebViewActivity.class);
            intent.putExtra(Global.INTENT_EXTRA_URL,
            mRequestToken.getAuthenticationURL());
            startActivityForResult(intent, TWITTER_SIGN_IN);
       }
    }
 }

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

@Override
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()
                      .getString(Global.URL_TWITTER_OAUTH_VERIFIER);
                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
                        e.printStackTrace();
                        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;
    }
    
    @Override
    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 >> " + 
                                accessToken.getTokenSecret());
            twitterResponse.setToken(accessToken.getToken());
            twitterResponse.setTokenSecret(accessToken.getTokenSecret());
            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);
                twitterResponse.setUser(user);
             }catch(TwitterException e) {
                 e.printStackTrace();
             }
         } catch (TwitterException e) {
               e.printStackTrace();
       }
       return twitterResponse;
    }
 
    @Override
    protected void onPostExecute(TwitterResponse result) {
         super.onPostExecute(result);
    }
}

We use AsyncTasks to prevent the NetworkOnMainThread exceptions

Advertisements