Android Twitter Integration Using twitter4j

In this tutorial we will see how to integrate twitter social media into android application , there might be a situation in your application were you want to  authenticate the user at the entry point of your application during such time you can force the user to login with twitter oauth login , in this post we will see twitter oauth login and  after login sending tweet from application and also logout from the twitter .




Create Twitter App


To enable application specific Consumer key & Consumer Secret key,

  1. Go to Twitter developer console https://apps.twitter.com/ .
  2. Click on “Create New App” .
  3. Under “Settings” tab, add the application details.
  4. Once you done with above procedure, click on “Permissions” tab to set the access “permission level”.
  5. Finally, Click on “Keys & Access Tokens” tab to get the “Consumer key” as well as “Secret Key”. 


Go to Twitter developer console https://apps.twitter.com/ Click on “Create New App”.


Fill the Application Details . if you don't have website , then fill  field fill any dummy value

 Under “Settings” tab, add the application details.


Once you done with above procedure, click on “Permissions” tab to set the access “permission level”.

Finally, Click on “Keys & Access Tokens” tab to get the “Consumer key” as well as “Secret Key”.

Building the project with twitter4j library


Download the Twitter4j (A Java library for the Twitter API) jar file  from http://twitter4j.org/en/ . and place inside the libs folder of project .

In the applications build.gradle file inside dependencies add "compile files('libs/twitter4j-core-4.0.3.jar')".

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile files('libs/twitter4j-core-4.0.3.jar')
}

String Constant


file : string.xml
<resources>
    <string name="app_name">AndroidTwitter</string>
    <string name="twitter_consumer_key">YOUR_CONSUMER_KEY_HERE</string>
    <string name="twitter_consumer_secret">YOUR_CONSUMER_SECRET_HERE</string>
</resources>


XML Layout


file : activity_main.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:overScrollMode="never">
   </android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:id="@+id/tweet_layout"
        style="@style/layoutstyle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar"
        android:background="#F3F3F3"
        android:orientation="vertical"
        android:visibility="gone"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/username_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Welcome"
            android:textSize="20sp" />

        <Button
            android:id="@+id/tweet_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/username_tv"
            android:background="@drawable/selector_option_button_bg"
            android:text="Tweet"
            android:textAllCaps="false"
            android:textSize="16sp" />


        <EditText
            android:id="@+id/et"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tweet_btn"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:background="@drawable/edittextstyle"
            android:gravity="top|left"
            android:textColor="#000000" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/twitter_login_layout"
        style="@style/layoutstyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/prod_reg_social_border_btn">

        <Button
            android:id="@+id/twitter_login_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/dc_twitter"
            android:text="Twitter"
            android:textAllCaps="false"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:textStyle="bold" />
    </RelativeLayout>

</RelativeLayout>




file : authenticate_webview.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>

</LinearLayout>


MainActivity


file : MainActivity.java
package androidtwitter.tutorialsbuzz.com.androidtwitter;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    public static final String PREF_NAME = "sample_twitter_pref";
    public static final String PREF_USER_NAME = "twitter_user_name";
    public static final int WEBVIEW_REQUEST_CODE = 100;
    private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    private static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";

    private  EditText mEditText = null;
    private Button tweet_btn = null, twitter_login_btn = null;
    private RelativeLayout mtweet_layout = null, mtwitter_login_layout = null;
    private TextView username_tv = null;

    private ProgressDialog mPostProgress = null;

    private String mConsumerKey = null;
    private String mConsumerSecret = null;
    private String mCallbackUrl = null;
    private String mAuthVerifier = null;
    private String mTwitterVerifier = null;
    private Twitter mTwitter = null;
    private RequestToken mRequestToken = null;
    private SharedPreferences mSharedPreferences = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        setContentView(R.layout.activity_main);
        initViews();
        initSDK();
        tweet_btn.setOnClickListener(this);
        twitter_login_btn.setOnClickListener(this);
    }

    private void initViews() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().show();
        mEditText = (EditText) findViewById(R.id.et);
        tweet_btn = (Button) findViewById(R.id.tweet_btn);
        twitter_login_btn = (Button) findViewById(R.id.twitter_login_btn);
        username_tv = (TextView) findViewById(R.id.username_tv);
        mtweet_layout = (RelativeLayout) findViewById(R.id.tweet_layout);
        mtwitter_login_layout = (RelativeLayout) findViewById(R.id.twitter_login_layout);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tweet_btn:
                String tweetText = mEditText.getText().toString();
                new PostTweet().execute(tweetText);
                break;
            case R.id.twitter_login_btn:
                mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
                if (isAuthenticated()) {
                    Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
                    mtweet_layout.setVisibility(View.GONE);
                    mtwitter_login_layout.setVisibility(View.VISIBLE);
                } else {
                    loginToTwitter();
                }
                break;
        }
    }
    private void closeProgress() {
        if (mPostProgress != null && mPostProgress.isShowing()) {
            mPostProgress.dismiss();
            mPostProgress = null;
        }
    }
    //TwitterAuthentication
    public void initSDK() {
        mConsumerKey = getResources().getString(R.string.twitter_consumer_key);
        mConsumerSecret = getResources().getString(R.string.twitter_consumer_secret);
        mAuthVerifier = "oauth_verifier";

        if (TextUtils.isEmpty(mConsumerKey)
                || TextUtils.isEmpty(mConsumerSecret)) {
            return;
        }

        mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
        if (isAuthenticated()) {
            Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
            //hide login button here and show tweet
            mtweet_layout.setVisibility(View.VISIBLE);
            mtwitter_login_layout.setVisibility(View.GONE);
            mSharedPreferences.getString(PREF_USER_NAME, "");
            username_tv.setText("Welcome n" + mSharedPreferences.getString(PREF_USER_NAME, ""));

        } else {
            mtweet_layout.setVisibility(View.GONE);
            mtwitter_login_layout.setVisibility(View.VISIBLE);
            Uri uri = getIntent().getData();

            if (uri != null && uri.toString().startsWith(mCallbackUrl)) {
                String verifier = uri.getQueryParameter(mAuthVerifier);
                try {
                    AccessToken accessToken = mTwitter.getOAuthAccessToken(
                            mRequestToken, verifier);
                    saveTwitterInformation(accessToken);
                    Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
                    Log.d("Failed to login ",
                            e.getMessage());
                }
            }
        }
    }

    protected boolean isAuthenticated() {
        return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
    }

    private void saveTwitterInformation(AccessToken accessToken) {
        long userID = accessToken.getUserId();
        User user;
        try {
            user = mTwitter.showUser(userID);
            String username = user.getName();
            SharedPreferences.Editor e = mSharedPreferences.edit();
            e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
            e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
            e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
            e.putString(PREF_USER_NAME, username);
            e.commit();

        } catch (TwitterException e1) {
            Log.d("Failed to Save", e1.getMessage());
        }
    }

    private void loginToTwitter() {
        boolean isLoggedIn = mSharedPreferences.getBoolean(
                PREF_KEY_TWITTER_LOGIN, false);

        if (!isLoggedIn) {
            final ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(mConsumerKey);
            builder.setOAuthConsumerSecret(mConsumerSecret);

            final Configuration configuration = builder.build();
            final TwitterFactory factory = new TwitterFactory(configuration);
            mTwitter = factory.getInstance();
            try {
                mRequestToken = mTwitter.getOAuthRequestToken(mCallbackUrl);
                startWebAuthentication();
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
    }

    protected void startWebAuthentication() {
        final Intent intent = new Intent(MainActivity.this,
                TwitterAuthenticationActivity.class);
        intent.putExtra(TwitterAuthenticationActivity.EXTRA_URL,
                mRequestToken.getAuthenticationURL());
        startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null)
            mTwitterVerifier = data.getExtras().getString(mAuthVerifier);

        AccessToken accessToken;
        try {
            accessToken = mTwitter.getOAuthAccessToken(mRequestToken,
                    mTwitterVerifier);

            long userID = accessToken.getUserId();
            final User user = mTwitter.showUser(userID);
            String username = user.getName();
            username_tv.setText("Welcomen " + username);

            mtweet_layout.setVisibility(View.VISIBLE);
            mtwitter_login_layout.setVisibility(View.GONE);
            saveTwitterInformation(accessToken);
        } catch (Exception e) {
        }
    }

    Private class PostTweet extends AsyncTask<String, Integer, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mPostProgress = new ProgressDialog(MainActivity.this);
            mPostProgress.setMessage("Loading...");
            mPostProgress.setCancelable(false);
            mPostProgress.show();
        }

        @Override
        protected Void doInBackground(String... params) {

            String status = params[0];
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(mConsumerKey);
            builder.setOAuthConsumerSecret(mConsumerSecret);

            SharedPreferences mSharedPreferences = null;
            mSharedPreferences =
                    getSharedPreferences(PREF_NAME, 0);
            String access_token = mSharedPreferences.getString(
                    PREF_KEY_OAUTH_TOKEN, "");
            String access_token_secret = mSharedPreferences.getString(
                    PREF_KEY_OAUTH_SECRET, "");
            Log.d("Async", "Consumer Key in Post Process : "
                    + access_token);
            Log.d("Async", "Consumer Secreat Key in post Process : "
                    + access_token_secret);

            AccessToken accessToken = new AccessToken(access_token,
                    access_token_secret);
            Twitter twitter = new TwitterFactory(builder.build())
                    .getInstance(accessToken);
            try {
                if (status.length() < 139) {
                    StatusUpdate statusUpdate = new StatusUpdate(status);
                    twitter4j.Status response = twitter.updateStatus(statusUpdate);
                    Log.d("Status", response.getText());
                }
            } catch (TwitterException e) {
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void Result) {
            mEditText.setText("");
            closeProgress();
        }
    }

}

Twitter Authentication


file : TwitterAuthenticationActivity.java
package androidtwitter.tutorialsbuzz.com.androidtwitter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class TwitterAuthenticationActivity extends Activity {
    public final static String EXTRA_URL = "extra_url";
    private static final String TAG = TwitterAuthenticationActivity.class
            .getSimpleName();
    private WebView mWebView = null;
    private ProgressDialog mDialog = null;
    private Activity mActivity = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        setContentView(R.layout.authenticate_webview);
        mWebView = (WebView) findViewById(R.id.webview);
        final String url = this.getIntent().getStringExtra(EXTRA_URL);
        if (url== null) {
            finish();
        }
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.loadUrl(url);
    }

    @Override
    protected void onStop() {
        cancelProgressDialog();
        super.onStop();
    }

    @Override
    protected void onPause() {
        cancelProgressDialog();
        super.onPause();
    }

    private void cancelProgressDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog.cancel();
            mDialog = null;
        }
    }

    @Override
    protected void onResume() {
        this.onRestart();
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            try {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                    mDialog = null;
                }
            } catch (Exception exception) {
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (mDialog == null)
                mDialog = new ProgressDialog(TwitterAuthenticationActivity.this);
            mDialog.setMessage("Loading..");

            if (!(mActivity.isFinishing())) {
                mDialog.show();
            }
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            Log.i(TAG, "Loading Resources");
            Log.i(TAG,
                    "Resource Loading Progress : " + view.getProgress());
            if (view.getProgress() >= 70) {
                cancelProgressDialog();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);
            String verifier = uri.getQueryParameter("oauth_verifier");
            Intent resultIntent = new Intent();
            resultIntent.putExtra("oauth_verifier", verifier);
            setResult(RESULT_OK, resultIntent);
            finish();
            return true;

        }
    }
}


Android Manifest


file : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="androidtwitter.tutorialsbuzz.com.androidtwitter" >

    <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
     
<activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".TwitterAuthenticationActivity">
        </activity>

    </application>

</manifest>








7 comments:

vydyabhushana siddhu said...

Nicce post

Sathish Jaganathan said...

Superb Concept and Well Explanation
It is possible to get user's Mail ID ? like Facebook Integration??

Артемий Терехов said...

this is old technology. need use fabric sdk - official twitter sdk.

Pawan Deshpande said...

Thank you

Pawan Deshpande said...

I have covered this at http://www.tutorialsbuzz.com/2015/09/Android-Twitter-oAuth-Connect-fabric-plugin.html

Артемий Терехов said...

It's OK, thanks.
Good idea write about other opportunities of fabric.

Pawan Deshpande said...

long userID = accessToken.getUserId();
final User user = mTwitter.showUser(userID);

from the above user object you can make api call to retrieve user information like name, id and emailID etc

Post a Comment