Integrating twitter in your android application will make user easily login into your app using their twitter account which avoids filling a long registration forms. In this tutorial i explained how to integrate twitter in your android application using twitter oAuth procedure. This is very basic tutorial with simple login and updating twitter status message.

Download Code

Registering twitter app – getting Consumer Key & Consumer Secret

In order to implement twitter oAuth in your application you need twitter consumer key and consumer secret which are used to make twitter API calls. So register a new twitter application and get the keys. Check the following video about creating a twitter app

1. Go to https://dev.twitter.com/apps/new and register new application. Fill application name, description and website.
2. Give some dummy url in the callback url field to make the app as browser app. (If you leave it as blank it will act as Desktop app which won’t work in mobile device)

android registering twitter application

3. Under the settings tab upload icon and change the access type to Read and Write.

android registering twitter application uploading icon

4. Copy Consumer Key & Consumer Secret key

android registering twitter application consumer key & secret

Downloading twitter4j library

In this tutorial to integrate twitter i used one of the most popular libraries twitter4j. You can read their official documentation to know more about it.

1. Download & extract twitter4j library from twitter4j-android-2.2.6.zip (slimmed version for Android platform). Here is the direct link

Creating new Project

In this tutorial i explained basic twitter API calls login and updating status only. If you want to integrate more api calls like reading users tweet timeline, sending direct message etc., you need to include other required .jar files too. Read more Code Examples to get know the usage.

1. Create a new project in Eclipse File New ⇒ Android ⇒ Application Project and fill the required details.
After creating project open AndroidManifest.xml file and paste the following code. I added following code to manifest file

– INTERNET Permission
– ACCESS_NETWORK_STATE Permission
– and added an Intent Filter

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.twitterconnect"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <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="t4jsample"/>
            </intent-filter>
        </activity>
    </application>
    
    <!-- Permission - Internet Connect -->
    <uses-permission android:name="android.permission.INTERNET" />
    
    <!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest>

2. Copy the required twitter4j .jar files into your project’s libs folder. In this tutorial i copied twitter4j-core-android-2.2.6 as it is the only required file in this tutorial.

android twitter4j jar files
android adding twitter4j jar files to project

3. Before getting into twitter integration i am including two quick class files to the project. Create a new class file called AlertDialogManager.java and paste the following code. This class file used to show alert dialog.

package com.androidhive.twitterconnect;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AlertDialogManager {
	/**
	 * Function to display simple Alert Dialog
	 * @param context - application context
	 * @param title - alert dialog title
	 * @param message - alert message
	 * @param status - success/failure (used to set icon)
	 * 				 - pass null if you don't want icon
	 * */
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		if(status != null)
			// Setting alert dialog icon
			alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}
}

4. Create another class file named ConnectionDetector.java and paste the following code. This class is used to detect internet connection status.

package com.androidhive.twitterconnect;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
 
public class ConnectionDetector {
 
    private Context _context;
 
    public ConnectionDetector(Context context){
        this._context = context;
    }
 
    /**
     * Checking for all possible internet providers
     * **/
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
    }
}

5. Open your activity_main.xml file and type the following code. In the following code i am placing login button, update status edittext and update status button. By default all the ui elements will be hidden except login button.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <!-- Twitter Login Button -->
    <Button android:id="@+id/btnLoginTwitter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Login with Twitter"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="30dip"/>
    
    <!-- user name label -->
    <TextView android:id="@+id/lblUserName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_marginTop="30dip"/>

    <!-- label update status -->
    <TextView android:id="@+id/lblUpdate" 
        android:text="Update Status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:visibility="gone"/>
    
    <!-- Tweet EditText -->
    <EditText android:id="@+id/txtUpdateStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:visibility="gone"/>
    
    <!-- Tweet Button -->
    <Button android:id="@+id/btnUpdateStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Tweet"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:visibility="gone"/>
    
    <!-- Twitter Logout button -->
    <Button android:id="@+id/btnLogoutTwitter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Logout from Twitter"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="50dip"
        android:visibility="gone"/>

</LinearLayout>

6. Now open your main activity class (In my case MainActivity.java) file and type the following code. In the following code i am declaring required variables.

package com.androidhive.twitterconnect;

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;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	// Constants
	/**
	 * Register your here app https://dev.twitter.com/apps/new and get your
	 * consumer key and secret
	 * */
	static String TWITTER_CONSUMER_KEY = "LsCQaPOwd8k7WkyRFRZF4Q";
	static String TWITTER_CONSUMER_SECRET = "KJbJu5IQrlwxW7Cwnax3mMzAc4j3n6Wd2dG125srgk";

	// Preference Constants
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

	static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	// Twitter oauth urls
	static final String URL_TWITTER_AUTH = "auth_url";
	static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	// Login button
	Button btnLoginTwitter;
	// Update status button
	Button btnUpdateStatus;
	// Logout button
	Button btnLogoutTwitter;
	// EditText for update
	EditText txtUpdate;
	// lbl update
	TextView lblUpdate;
	TextView lblUserName;

	// Progress dialog
	ProgressDialog pDialog;

	// Twitter
	private static Twitter twitter;
	private static RequestToken requestToken;
	
	// Shared Preferences
	private static SharedPreferences mSharedPreferences;
	
	// Internet Connection detector
	private ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}
		
		// Check if twitter keys are set
		if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
			// stop executing code by return
			return;
		}

		// All UI elements
		btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
		btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
		btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
		txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
		lblUpdate = (TextView) findViewById(R.id.lblUpdate);
		lblUserName = (TextView) findViewById(R.id.lblUserName);

		// Shared Preferences
		mSharedPreferences = getApplicationContext().getSharedPreferences(
				"MyPref", 0);

Login with Twitter Account

Login with twitter account in your android application involves following process.

First user asked to authenticate into your application using their twitter account.
Once user successfully logged into his twitter account we will receive his oauth token and oauth secret.
oauth token and oauth secret will be stored in android application shared preferences.
Whenever you need oauth tokens, you can read from shared preferences.
Once user clicks logout button we will delete oauth token & secret from shared prefrences

7. Open your main activity and write click event for login button.

> In click event i am calling loginToTwitter().
> Once the user logins into twitter he will be redirected to your android app again with oauth verifier.
> Using oauth verifier we do another request to get access token and access token secret.

		/**
		 * Twitter login button click event will call loginToTwitter() function
		 * */
		btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call login twitter function
				loginToTwitter();
			}
		});

		/** This if conditions is tested once is
		 * redirected from twitter page. Parse the uri to get oAuth
		 * Verifier
		 * */
		if (!isTwitterLoggedInAlready()) {
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
				// oAuth verifier
				String verifier = uri
						.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

				try {
					// Get the access token
					AccessToken accessToken = twitter.getOAuthAccessToken(
							requestToken, verifier);

					// Shared Preferences
					Editor e = mSharedPreferences.edit();

					// After getting access token, access token secret
					// store them in application preferences
					e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(PREF_KEY_OAUTH_SECRET,
							accessToken.getTokenSecret());
					// Store login status - true
					e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
					e.commit(); // save changes

					Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

					// Hide login button
					btnLoginTwitter.setVisibility(View.GONE);

					// Show Update Twitter
					lblUpdate.setVisibility(View.VISIBLE);
					txtUpdate.setVisibility(View.VISIBLE);
					btnUpdateStatus.setVisibility(View.VISIBLE);
					btnLogoutTwitter.setVisibility(View.VISIBLE);
					
					// Getting user details from twitter
					// For now i am getting his name only
					long userID = accessToken.getUserId();
					User user = twitter.showUser(userID);
					String username = user.getName();
					
					// Displaying in xml ui
					lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
				}
			}
		}

	}

and code for loginToTwitter() function is

/**
	 * Function to login twitter
	 * */
	private void loginToTwitter() {
		// Check if already logged in
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();
			
			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			try {
				requestToken = twitter
						.getOAuthRequestToken(TWITTER_CALLBACK_URL);
				this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse(requestToken.getAuthenticationURL())));
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else {
			// user already logged into twitter
			Toast.makeText(getApplicationContext(),
					"Already Logged into twitter", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Check user already logged in your application using twitter Login flag is
	 * fetched from Shared Preferences
	 * */
	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
	}
android twitter login
android twitter login oauth
android twitter login get username

Update Twitter Status

8. Once you login with twitter account you can see interface to update the status. Open your main activity class write a click event for update status button.

> In the following code async thread updateTwitterStatus() is called on clicking update status button.

/**
		 * Button click event to Update Status, will call updateTwitterStatus()
		 * function
		 * */
		btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Call update status function
				// Get the status from EditText
				String status = txtUpdate.getText().toString();

				// Check for blank text
				if (status.trim().length() > 0) {
					// update status
					new updateTwitterStatus().execute(status);
				} else {
					// EditText is empty
					Toast.makeText(getApplicationContext(),
							"Please enter status message", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

and code for updateTwitterStatus() async task is

	/**
	 * Function to update status
	 * */
	class updateTwitterStatus extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Updating to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			try {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
				builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
				
				// Access Token 
				String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
				// Access Token Secret
				String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
				
				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
				
				// Update status
				twitter4j.Status response = twitter.updateStatus(status);
				
				Log.d("Status", "> " + response.getText());
			} catch (TwitterException e) {
				// Error in updating status
				Log.d("Twitter Update Error", e.getMessage());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog and show
		 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
		 * from background thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(),
							"Status tweeted successfully", Toast.LENGTH_SHORT)
							.show();
					// Clearing EditText field
					txtUpdate.setText("");
				}
			});
		}

	}
android twitter update status
andorid update twitter status

Logout from Twitter

9. Open your main activity and write a click event for logout button. Please remember this logout code won’t logout user from the twitter in the browser. It will just clear the access tokens from your application shared preferences.

		/**
		 * Button click event for logout from twitter
		 * */
		btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call logout twitter function
				logoutFromTwitter();
			}
		});

and code for logoutFromTwitter() function is

	/**
	 * Function to logout from twitter
	 * It will just clear the application shared preferences
	 * */
	private void logoutFromTwitter() {
		// Clear the shared preferences
		Editor e = mSharedPreferences.edit();
		e.remove(PREF_KEY_OAUTH_TOKEN);
		e.remove(PREF_KEY_OAUTH_SECRET);
		e.remove(PREF_KEY_TWITTER_LOGIN);
		e.commit();

		// After this take the appropriate action
		// I am showing the hiding/showing buttons again
		// You might not needed this code
		btnLogoutTwitter.setVisibility(View.GONE);
		btnUpdateStatus.setVisibility(View.GONE);
		txtUpdate.setVisibility(View.GONE);
		lblUpdate.setVisibility(View.GONE);
		lblUserName.setText("");
		lblUserName.setVisibility(View.GONE);

		btnLoginTwitter.setVisibility(View.VISIBLE);
	}

Final Code:

Final code of MainActivity.java

package com.androidhive.twitterconnect;

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;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	// Constants
	/**
	 * Register your here app https://dev.twitter.com/apps/new and get your
	 * consumer key and secret
	 * */
	static String TWITTER_CONSUMER_KEY = "LsCQaPOwd8k7WkyRFRZF4Q";
	static String TWITTER_CONSUMER_SECRET = "KJbJu5IQrlwxW7Cwnax3mMzAc4j3n6Wd2dG125srgk";

	// Preference Constants
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

	static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	// Twitter oauth urls
	static final String URL_TWITTER_AUTH = "auth_url";
	static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	// Login button
	Button btnLoginTwitter;
	// Update status button
	Button btnUpdateStatus;
	// Logout button
	Button btnLogoutTwitter;
	// EditText for update
	EditText txtUpdate;
	// lbl update
	TextView lblUpdate;
	TextView lblUserName;

	// Progress dialog
	ProgressDialog pDialog;

	// Twitter
	private static Twitter twitter;
	private static RequestToken requestToken;
	
	// Shared Preferences
	private static SharedPreferences mSharedPreferences;
	
	// Internet Connection detector
	private ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}
		
		// Check if twitter keys are set
		if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
			// stop executing code by return
			return;
		}

		// All UI elements
		btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
		btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
		btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
		txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
		lblUpdate = (TextView) findViewById(R.id.lblUpdate);
		lblUserName = (TextView) findViewById(R.id.lblUserName);

		// Shared Preferences
		mSharedPreferences = getApplicationContext().getSharedPreferences(
				"MyPref", 0);

		/**
		 * Twitter login button click event will call loginToTwitter() function
		 * */
		btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call login twitter function
				loginToTwitter();
			}
		});

		/**
		 * Button click event to Update Status, will call updateTwitterStatus()
		 * function
		 * */
		btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Call update status function
				// Get the status from EditText
				String status = txtUpdate.getText().toString();

				// Check for blank text
				if (status.trim().length() > 0) {
					// update status
					new updateTwitterStatus().execute(status);
				} else {
					// EditText is empty
					Toast.makeText(getApplicationContext(),
							"Please enter status message", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

		/**
		 * Button click event for logout from twitter
		 * */
		btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Call logout twitter function
				logoutFromTwitter();
			}
		});

		/** This if conditions is tested once is
		 * redirected from twitter page. Parse the uri to get oAuth
		 * Verifier
		 * */
		if (!isTwitterLoggedInAlready()) {
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
				// oAuth verifier
				String verifier = uri
						.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

				try {
					// Get the access token
					AccessToken accessToken = twitter.getOAuthAccessToken(
							requestToken, verifier);

					// Shared Preferences
					Editor e = mSharedPreferences.edit();

					// After getting access token, access token secret
					// store them in application preferences
					e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(PREF_KEY_OAUTH_SECRET,
							accessToken.getTokenSecret());
					// Store login status - true
					e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
					e.commit(); // save changes

					Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

					// Hide login button
					btnLoginTwitter.setVisibility(View.GONE);

					// Show Update Twitter
					lblUpdate.setVisibility(View.VISIBLE);
					txtUpdate.setVisibility(View.VISIBLE);
					btnUpdateStatus.setVisibility(View.VISIBLE);
					btnLogoutTwitter.setVisibility(View.VISIBLE);
					
					// Getting user details from twitter
					// For now i am getting his name only
					long userID = accessToken.getUserId();
					User user = twitter.showUser(userID);
					String username = user.getName();
					
					// Displaying in xml ui
					lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
				}
			}
		}

	}

	/**
	 * Function to login twitter
	 * */
	private void loginToTwitter() {
		// Check if already logged in
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();
			
			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			try {
				requestToken = twitter
						.getOAuthRequestToken(TWITTER_CALLBACK_URL);
				this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse(requestToken.getAuthenticationURL())));
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else {
			// user already logged into twitter
			Toast.makeText(getApplicationContext(),
					"Already Logged into twitter", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Function to update status
	 * */
	class updateTwitterStatus extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Updating to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			try {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
				builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
				
				// Access Token 
				String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
				// Access Token Secret
				String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
				
				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
				
				// Update status
				twitter4j.Status response = twitter.updateStatus(status);
				
				Log.d("Status", "> " + response.getText());
			} catch (TwitterException e) {
				// Error in updating status
				Log.d("Twitter Update Error", e.getMessage());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog and show
		 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
		 * from background thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(),
							"Status tweeted successfully", Toast.LENGTH_SHORT)
							.show();
					// Clearing EditText field
					txtUpdate.setText("");
				}
			});
		}

	}

	/**
	 * Function to logout from twitter
	 * It will just clear the application shared preferences
	 * */
	private void logoutFromTwitter() {
		// Clear the shared preferences
		Editor e = mSharedPreferences.edit();
		e.remove(PREF_KEY_OAUTH_TOKEN);
		e.remove(PREF_KEY_OAUTH_SECRET);
		e.remove(PREF_KEY_TWITTER_LOGIN);
		e.commit();

		// After this take the appropriate action
		// I am showing the hiding/showing buttons again
		// You might not needed this code
		btnLogoutTwitter.setVisibility(View.GONE);
		btnUpdateStatus.setVisibility(View.GONE);
		txtUpdate.setVisibility(View.GONE);
		lblUpdate.setVisibility(View.GONE);
		lblUserName.setText("");
		lblUserName.setVisibility(View.GONE);

		btnLoginTwitter.setVisibility(View.VISIBLE);
	}

	/**
	 * Check user already logged in your application using twitter Login flag is
	 * fetched from Shared Preferences
	 * */
	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
	}

	protected void onResume() {
		super.onResume();
	}

}
This image is for thumbnail purpose
android twitter connect
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • mangesh kaduskar

    try to use twitter4j 3.0 in your project. it works for me

  • mangesh kaduskar

    hi Ravi,

    just because of ur tutorial i solved my lots of programming problems so thanks to u.

    but i suggest you some changes.

    1. when i login and visible buttons and textbox at that time if i click on back button it goes to twitter login page.

    can you implement startActivityForResult method in your program.

    2. AsyncTask should be implement in this example for login.

    3. Get data from twitter in main thread cause network on main thread exception.

  • aaron@wiredd.in

    there is no request token for this page

  • Navdeep Agrawal

    still my status can’t twit on twitter although I got success toast on click of tweet button

  • Guest

    Hey,

    Ive done everything you said in the tutorial. However, after i enter my username & password the following happens:

    1)

    The webpage at oauth://t4jsample?oauth_token=OSbp3U1QZh0DzCnDagbyf7mMtxzunjL1PO76KCgwwE&oauth_verifier=QuB89J1So4V4IrtOdcTa6poQ133S86BQwyprbDLsQ might be down or moved to another address..

    2)

    I get the following error in the logcat:

    ERROR/Tab(375): onReceivedError -10 oauth://t4jsample?oauth_token=OSbp3U1QZh0DzCnDagbyf7mMtxzunjL1PO76KCgwwE&oauth_verifier=QuB89J1So4V4IrtOdcTa6poQ133S86BQwyprbDLsQ The protocol is not supported.

    ANY HELP PLZZZZZZZ

  • Gemei

    You will have to write this code in your twitter login activity in the mainifest >>>

    ————————————————————————
    Now you will get the intent from the browser and uri wouldn’t return null anymore 🙂

    • Rocky

      Didn’t work. Any other suggesions?

      • Jaison

        did u find the solution for this issue …..
        Now i met the problem for couple of days i tried to find the solution …but my tries became failed

  • Marius

    I get a null point for AccesToken (i can’t understand why)

    i used this example and more others ()

    E/Twitter Login Error(10411): > null
    I used :
    MainActivity.this.accessToken = twitter.getOAuthAccessToken(
    requestToken, verifier);

    and
    accessToken = twitter.getOAuthAccessToken(
    requestToken, verifier);

    • Twinkle

      I get the same situation.. did you get solution?

    • John

      Same here as well. Any solution for this?

    • Paky

      PUT
      ” MainActivity.this.accessToken = twitter.getOAuthAccessToken(requestToken, verifier);”

      in a AsyncTask

  • alex

    Appropriate Callback URL for android app?

  • Nidhi Gupta

    hi.. i am using twitter4j to make android twitter linked app.. i am facing a problem in login.. in my app i used a login button,after successful login i want the second activity should open.. but everytime after logging in,the first activity opens showing login button again and again, i have used this code.. package com.twitter_demo_project;

    import oauth.signpost.OAuthConsumer;

    import oauth.signpost.OAuthProvider;

    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;

    import android.annotation.SuppressLint;

    import android.app.Activity;

    import android.app.ProgressDialog;

    import android.content.Intent;

    import android.content.SharedPreferences;

    import android.content.SharedPreferences.Editor;

    import android.content.pm.ActivityInfo;

    import android.net.Uri;

    import android.os.Build;

    import android.os.Bundle;

    import android.os.StrictMode;

    import android.util.Log;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.Button;

    import android.widget.TextView;

    import android.widget.Toast;

    @SuppressLint(“NewApi”)

    public class TwitterLoginActivity extends Activity {

    TextView tv;

    Button loginBtn;

    private OAuthConsumer consumer;

    private OAuthProvider provider;

    private ConnectionDetector cd;

    Twitter twitter;

    ProgressDialog pDialog;

    private static SharedPreferences mSharedPreferences;

    AlertDialogManager alert = new AlertDialogManager();

    RequestToken requestToken;

    private static final String CONSUMER_KEY = “********************”;

    private static final String CONSUMER_SECRET = “****************”;

    static String PREFERENCE_NAME = “twitter_oauth”;

    static final String PREF_KEY_OAUTH_TOKEN = “oauth_token”;

    static final String PREF_KEY_OAUTH_SECRET = “oauth_token_secret”;

    static final String PREF_KEY_TWITTER_LOGIN = “isTwitterLogedIn”;

    // static final String TWITTER_CALLBACK_URL = “oauth://t4jsample”;

    static final String URL_TWITTER_AUTH = “auth_url”;

    static final String URL_TWITTER_OAUTH_VERIFIER = “oauth_verifier”;

    static final String URL_TWITTER_OAUTH_TOKEN = “oauth_token”;

    public static final String OAUTH_CALLBACK_SCHEME = “x-oauthflow-twitter”;

    public static final String OAUTH_CALLBACK_HOST = “callback”;

    public static final String TWITTER_CALLBACK_URL = OAUTH_CALLBACK_SCHEME

    + “://” + OAUTH_CALLBACK_HOST;

    /*

    * public void storeAccessToken(AccessToken aToken) { SharedPreferences.Editor

    * editor = mSharedPreferences.edit(); editor.putString(PREF_KEY_OAUTH_TOKEN,

    * aToken.getToken()); editor.putString(PREF_KEY_OAUTH_SECRET,

    * aToken.getTokenSecret()); editor.commit(); }

    */

    protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub

    setContentView(R.layout.twitter_login);

    super.onCreate(savedInstanceState);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    if (android.os.Build.VERSION.SDK_INT > 9) {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    }

    cd = new ConnectionDetector(getApplicationContext());

    if (!cd.isConnectingToInternet()) {

    alert.showAlertDialog(TwitterLoginActivity.this,

    “Internet Connection Error”,

    “Please connect to working Internet connection”, false);

    return;

    }

    if (CONSUMER_KEY.trim().length() == 0

    || CONSUMER_SECRET.trim().length() == 0) {

    // Internet Connection is not present

    alert.showAlertDialog(TwitterLoginActivity.this, “Twitter oAuth tokens”,

    “Please set your twitter oauth tokens first!”, false);

    // stop executing code by return

    return;

    }

    tv = (TextView) findViewById(R.id.welcome_txt);

    loginBtn = (Button) findViewById(R.id.login_btn);

    mSharedPreferences = getApplicationContext().getSharedPreferences(“MyPref”,

    0);

    loginBtn.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated method stub

    Thread th = new Thread(new Runnable() {

    public void run() {

    loginToTwitter();

    }

    });

    th.start();

    }

    });

    if (!isTwitterLoggedInAlready()) {

    Uri uri = getIntent().getData();

    if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {

    // oAuth verifier

    String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

    try {

    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,

    verifier);

    Editor e = mSharedPreferences.edit();

    e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());

    e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());

    // Store login status – true

    e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);

    e.commit();

    Log.e(“Twitter OAuth Token”, “> ” + accessToken.getToken());

    }

    catch (Exception e) {

    // Check log for login errors

    Log.e(“Twitter Login Error”, “> ” + e.getMessage());

    }

    }

    }

    }

    public void loginToTwitter() {

    if (!isTwitterLoggedInAlready()) {

    ConfigurationBuilder builder = new ConfigurationBuilder();

    builder.setOAuthConsumerKey(CONSUMER_KEY);

    builder.setOAuthConsumerSecret(CONSUMER_SECRET);

    Configuration configuration = builder.build();

    TwitterFactory factory = new TwitterFactory(configuration);

    twitter = factory.getInstance();

    try {

    requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);

    this.startActivity(new Intent(Intent.ACTION_VIEW, Uri

    .parse(requestToken.getAuthenticationURL())));

    }

    catch (TwitterException e) {

    e.printStackTrace();

    }

    }

    else {

    Intent i = new Intent(TwitterLoginActivity.this, TweetsListActivity.class);

    startActivity(i);

    }

    }

    private boolean isTwitterLoggedInAlready() {

    return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

    }

    protected void onResume() {

    super.onResume();

    }

    }

  • tomer

    Hello, very nice post, thank you.

    My problem is that after i log in the app redirects me to my main activity and not to the activity where i called loginToTwitter()

    Because of that i dont get the AccessToken.

    How can i solve it?

  • sand

    hey… nothing happens when i click Login With Twitter??? what do i do??

  • wishy

    Ahan! Wonderful nice tutorial.
    It helps me a lot. Could you also post something related to how to use twitter search API?

  • Do Huu Tien

    I built your app and it always return back the callback url page, not showing the app. How can I fix it?

    • Kristina Ferm

      Mine does that, too.. I’m not sure if I’ve got the wrong “TWITTER_CALLBACK_URL” or if it’s something else. Would greatly appreciate a solution..

  • Rocky

    Hey! I couldn’t figure it out yet. Can you help me?

  • Rocky

    Did you get it working?

  • abhay

    same problem i am facing.. did you get any solution?

  • pratik parekh

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    add this code in your main activity under setContetnView

    • Avinash

      Even i too getting same issue. and as u said added the above code under setContentView.

      After adding am not able to import the StrictMode. What can i do now and please help me out.

  • Moonlike Moonlygirl

    How can i migrate to API v1.1. to this project.. Because when I post tweet i show “Status tweeted successfully”. But i did not see my tweet on twitter . so what shoul I do? please help mee

  • dedar

    after login on twitter i donot redirect back to app…what is the solution of this problem

  • lokendra

    when i am executing my app for tweeter integration it is giving some exception ….plzz any body can resolve it….network main thread exception

    • Avinash

      Right, even i too got the same..

      Plz update the below code under setContentView(.. MainActivity.java

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);

      it will resolve.

      • trfilmographer

        I tired this, but I am still getting “android.os.NetworkOnMainThreadException”

        • trfilmographer

          Ah, I got it working now without edits to your comment. THanks

  • harshad

    @Moonlike Moonlygirl …you are getting this error mean you are’nt added this jar: twitter4j-core-3.0.3.jar

  • TechtaSyS Yazılım

    Hey guys… For this example i found the solution…
    Here is what i’ve dont:

    I downloaded the source code from top.
    Opened project with existing code in eclipse.
    Changed android version of project to 4.1.2 from project properties

    Deleted old Twitter4J.jar from lib folder of the project and copied twitter4j-core-3.0.5.jar in lib folder

    And… here is the best part u should add some code in ur MainActivity.java

    Just change this;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    into this;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    It’ll say StrickMode didnt defined or sth else, just mouseover it and try import it from android.os

    That’s all folks.

    It worked well from me.. Tried every way on this example..
    Now, im on gettin user info from twitter… I’ll share codes a.s.a.p.

    • Elvira Chrisanty

      Hi, i am wondering if you have shared the way to get user info from twitter as you mentioned in this comment. Mind to share it since I am working on it but not successful yet.. thanks!

  • Guest777

    Nice Job!
    Thank you, this helped me alot!!!

  • Daeniight

    same with comments and question below. why twitter redirect me to login button again? and it’ll be the same when i repeated login

  • Gebriel13

    It is closing every time i click on Login botton. I am using source code and it doesnt working.

  • careful7j

    Everything in this example is just fine, except that twitter is not 1.1 api version, while code is based on 1.0 api and therefore doesnt work. Would be nice if someone fix this.

  • jay01

    I’m getting nullpointeexception at AccessToken accessToken = twitter.getOAuthAccessToken(
    requestToken, verifier); please helo me with this

  • girish

    What if another user wants to log in to twitter using same phone. There it displays as invalid request token and doesnot go to the next page. Its annoying. Plz help.!!

  • Juliatzin

    I needed to put a CountDownLatch so that accessToken = twitter.getOAuthAccessToken(requestToken, verifier); executes first

  • Im getting these errors, can anyone expalin it? Thank you.

    nullRelevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=10f5ada3 or
    http://www.google.co.jp/search?q=dceba048
    TwitterException{exceptionCode=[10f5ada3-dceba048 10f5ada3-dceba01e], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.6}

  • Im getting these errors, can someone explain what’s the problem? thanks 🙂

    02-04 19:58:02.941: E/TOKEN(2807): nullRelevant discussions can be found on the Internet at:

    02-04 19:58:02.941: E/TOKEN(2807): http://www.google.co.jp/search?q=10f5ada3 or

    02-04 19:58:02.941: E/TOKEN(2807): http://www.google.co.jp/search?q=dceba048

    02-04 19:58:02.941: E/TOKEN(2807): TwitterException{exceptionCode=[10f5ada3-dceba048 10f5ada3-dceba01e], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.6}

  • Kunal Sharma

    java.lang.NoClassDefFoundError: twitter4j.conf.ConfigurationBuilder any one having solution to this problem

  • Android developer

    While creating an application what is the significance of Callback URL? Does keeping this field empty make any difference?

    • Mgamerz

      If you don’t put a url there it thinks its a desktop and won’t return the data you want when you try to get the token.

  • Sandeep Armal

    Hi Ravi,

    I don’t understand why you add oauth://t4jsample as a twitter callback. TWITTER_CALLBACK_URL = “oauth://t4jsample”. I tried to add my app name but didn’t get app bak on my screen

    • json001

      i got this working.. the key to return to your app lies in the manifest file. you assign the TWITTER_CALLBACK_URL to the activity you want to return to..

      the part of the code you need to pay attention to is the android:host of the intent-filter..
      just assign the intent-filter to the activity you want the twitter to return to..
      also TWITTER_CALLBACK_URL and host shoulde be the same.. in this example its “t4jsample”

      • prasanna

        How do i assign TWITTER_CALLBACK_URL to the activity

        • Ayuchuco!

          In the AndroidManifest.xml file, put this intent filter inside the tag that corresponds to the activity you want to assign for. I’m pretty sure you have more intent filters declared inside each activity you use on your project, so that any one as example to how to put this intent filter inside it and avoid getting errors.

    • jem88

      Lot of respect for this workaround, thanks dude! 😉

  • Samolo

    Do you have find a solution for this issue?

    • Jaison

      Anyone find a solution for this issue

  • Samolo

    Put the instruction in a new Thread works.

  • MOhammed

    i tried to change it with more error .Plz . can you send the full source code to me .

    thank you

  • $neha

    I have error i.e No authentication changes found
    how can I solve this

  • Govinda Chandra Pradhan

    i have downloaded the source code and i am getting the error
    “Unfortunately, android twitter connect has stopped” can any one help me
    or mail me the working source code

    govindachandra_p@yahoo.com please …

  • Nico

    I got that problem too.

  • sandy

    03-19 09:24:00.328: E/AndroidRuntime(1481): FATAL EXCEPTION: main
    03-19 09:24:00.328: E/AndroidRuntime(1481): android.os.NetworkOnMainThreadException
    03-19 09:24:00.328: E/AndroidRuntime(1481): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    03-19 09:24:00.328: E/AndroidRuntime(1481): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
    03-19 09:24:00.328: E/AndroidRuntime(1481): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    03-19 09:24:00.328: E/AndroidRuntime(1481): at java.net.InetAddress.getAllByName(InetAddress.java:214)
    03-19 09:24:00.328: E/AndroidRuntime(1481): at libcore.net.http.HttpConnection.(HttpConnection.java:70)
    03-19 09:24:00.328: E/AndroidRuntime(1481): at libcore.net.http.HttpConnection.(HttpConnection.java:50)
    03-19 09:24:00.328: E/AndroidRuntime(1481): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)

    getting this error please help

    • Ayuchuco!

      It’s clear!!! It says “android.os.NetworkOnMainThreadException”; that means that all Internet calls, Server calls, anyway…. all calls you make to the web, must be on another thread!!! This calls cannot be done on the main thread

      • Slim Ben Abdelwahed

        what is the solution

  • Ankur Goyal

    03-21 02:08:32.725: E/AndroidRuntime(847): FATAL EXCEPTION: main

    03-21 02:08:32.725: E/AndroidRuntime(847): Process: com.example.updatewht, PID: 847

    03-21 02:08:32.725: E/AndroidRuntime(847): android.os.NetworkOnMainThreadException

    03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)

    03-21 02:08:32.725: E/AndroidRuntime(847): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)

    03-21 02:08:32.725: E/AndroidRuntime(847): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)

    03-21 02:08:32.725: E/AndroidRuntime(847): at java.net.InetAddress.getAllByName(InetAddress.java:214)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:254)

    03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:137)

    03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.HttpClientBase.request(HttpClientBase.java:53)

    03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.HttpClientBase.post(HttpClientBase.java:82)

    03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:116)

    03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:98)

    03-21 02:08:32.725: E/AndroidRuntime(847): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:287)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.example.updatewht.MainActivity.loginToTwitter(MainActivity.java:185)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.example.updatewht.MainActivity.access$1(MainActivity.java:171)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.example.updatewht.MainActivity$1.onClick(MainActivity.java:98)

    03-21 02:08:32.725: E/AndroidRuntime(847): at android.view.View.performClick(View.java:4438)

    03-21 02:08:32.725: E/AndroidRuntime(847): at android.view.View$PerformClick.run(View.java:18422)

    03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.Handler.handleCallback(Handler.java:733)

    03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.Handler.dispatchMessage(Handler.java:95)

    03-21 02:08:32.725: E/AndroidRuntime(847): at android.os.Looper.loop(Looper.java:136)

    03-21 02:08:32.725: E/AndroidRuntime(847): at android.app.ActivityThread.main(ActivityThread.java:5017)

    03-21 02:08:32.725: E/AndroidRuntime(847): at java.lang.reflect.Method.invokeNative(Native Method)

    03-21 02:08:32.725: E/AndroidRuntime(847): at java.lang.reflect.Method.invoke(Method.java:515)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

    03-21 02:08:32.725: E/AndroidRuntime(847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

    03-21 02:08:32.725: E/AndroidRuntime(847): at dalvik.system.NativeStart.main(Native Method)

    I got that bug….how can i resolve this bug….anyone can help me please

  • khoahihi

    I get Problem. when app execute then occur twitterexception message is : SSL handshake aborted: ssl=0x9805280: Failure in SSL library, usually a protocol error and error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:683 0x80a40440:0x00000000). This Exception appear when execute command requestToken=twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL); i do’nt understand reason. Please help me resolve this problem! Thanks

    • Twinkle

      update the twitter4j library to latest update , this will solve this problem

  • sathish

    this application is woring fine when i login the and update status it is not showing any thing just your message sent like thaat

  • Guest

    thanks for this tutor.
    i downloaded ur source code, but i get much error on mainActivity.java
    error on line :

    package com.androidhive.twitterconnect;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.content.pm.ActivityInfo;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.text.Html;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends Activity {

    and much more, can u help me to solve my problem? please

    • Ayuchuco!

      If you’re creating a project in Eclipse from a blank one and you are also copying only the files mentioned in this tutorial, yo should change the first line that reads “package com.androidhive.twitterconnect;” for the actual package you configured and where this class is

  • Anas Azeem

    After authenticating the app open the activity on Chrome. “How in the world can a browser open an Android ACTIVITY”???
    Can any wise person tell me how to redirect the app back to the “Android App (not the browser)”. I’ve tried using the

    android:launchMode=”singleTask”. Using this the control do return to the app, but all tokens and usernames which were were visible in the logcat before are not visible now.

    • Mgamerz

      The intent filter will catch the new link it’s trying to direct you to and it contains information the app is supposed to catch.

  • Syed Talha

    Can you please provide the proper Twitter logout

  • Dinesh Kumar A

    1.In my app contains twitter integration and I follow this code(class files (Not Download)) and i have error an while taping the Login Button Nothing was Happened.. Plz tell some Solution.

    2.When i download the Code , how to change a authorize app view in while opening the Dialog window

  • cnpisit

    i already for this tutorial but i still can’t get requestToken after login with twitter. i use twitter4j-core-4.0.1.jar library

  • Paula

    Thanks for the tutorial, but when I click in the Login Button Nothing Happened. If someone knows how to fix this, I’d be very grateful. Thanks!

  • prasad Vdv

    Thanks for the twitter login tutorial. I’m facing a problem that i can’t callback to my app.
    i use this code in my app. what will be changed in this following:

  • Young

    In your Project , when i click button ” Login with Twitter ” -> web brower is start to Login . So that in Screen Twitt Status when I press ” Back ” application return webBrowser .
    Who can start web as a Dialog to solve issuse ?

  • Young King

    I have aready Solve Issuse press ” Back ” application return webBrowser . Hi .

  • Sulaiman Khan

    thanks works properly…….

  • Boy Lenssen

    I’ve put the callback check not in the ‘onCreate’ but ‘onResume’, as onCreate will probably not be called as the activity is not recreated

  • Ajay Prasad

    How can we access the contact list of twitter ?? please help

  • Nikhil

    How is it working for most of the peopl? For me it says network on main thread exception?

    • Vineel Sadineni

      Use Async Task

    • junior

      Can you update the code above to reflect the network error correction? I am trying to use asynctask and it is not working

    • d

      if you solved this, can you post the code?

      • Try to add networking call code in AsyncTask block.

  • Kalai Selvi S

    How to add read & write permission to twitter app.It asks mobile number,when adding India(Airtel) mobile number it is not accepted

    • Roy

      Install twitter app on your phone and configure your phone on it…this worked for me.

  • Prince Kumar

    The Application is crashing as soon as i click login

  • saurabh

    Nothing happens when i lick on “Login With Twitter”

  • akhilesh

    “unfortunately android twitter connect has stopped” this error is occured when i press login button

    • Guest

      Me too,

    • Dung Nguyen VN

      Use it if your device or AVD is higher than API 9

      if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
      .permitAll().build();
      StrictMode.setThreadPolicy(policy);
      }

      Choose Project Build Target is higher than 9.
      Not 2.3.1 (API 9) or lower.
      Right-click on Project, choose Properties -> Android -> Choose Project Build Target -> OK.

      • akhilesh

        “Call requires API level 9 (current min is 8): new android.os.StrictMode.ThreadPolicy.Builder ” this error ocured while i added u r code..(am a beginer)

        • Dung Nguyen VN

          Choose Project Build Target is higher than 9.

          Not 2.3.1 (API 9) or lower.

          Right-click on Project, choose Properties -> Android -> Choose Project Build Target -> OK.

          • akhilesh

            it worked.. my problem is the twiter4j version problem

  • Dung Nguyen VN

    Use it if your device or AVD is higher than API 9

    if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }

    • akhilesh

      But nothing is happened when i click login with twiter button.. is that worked for u???

      • Dung Nguyen VN

        It worked for me.

        Choose Project Build Target is higher than 9.
        Not 2.3.1 (API 9) or lower.
        Right-click on Project, choose Properties -> Android -> Choose Project Build Target -> OK.

  • INDIAN

    This Toutorial is having some error 1) Login is done on Main Thread ,So it give Network on Main Thread error. That can be solved adding write Logintotwitter() method inside Asynktask and its callback after login is not handeled

    2)One More Error
    AccessToken accessToken = twitter.getOAuthAccessToken( verifier); you reqire only verifier

    • INDIAN

      This code has many bugs kindly update it

      • Zem

        Are you able to make this work ? if so, can you share your project on us ?
        Thank you so much.

        • INDIAN

          private class LoginToTwitterThread extends AsyncTask

          {

          ProgressDialog pdialog;

          @Override

          protected void onPreExecute()

          {

          pdialog = new ProgressDialog(MainActivity.this);

          pdialog.setMessage(“Please wait…”);

          pdialog.setCancelable(false);

          pdialog.show();

          super.onPreExecute();

          }

          @Override

          protected Void doInBackground(Void… params)

          {

          loginToTwitter();

          return null;

          }

          @Override

          protected void onPostExecute(Void result)

          {

          if (pdialog != null)

          {

          if (pdialog.isShowing())

          {

          pdialog.dismiss();

          }

          }

          super.onPostExecute(result);

          }

          }

          protected void loginToTwitter()

          {

          if (!isTwitterAlreadyLogedin())

          {

          ConfigurationBuilder builder=new ConfigurationBuilder();

          builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);

          builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

          builder.setDebugEnabled(true);

          Configuration confrigation=builder.build();

          TwitterFactory factory=new TwitterFactory(confrigation);

          twitter=factory.getInstance();

          try

          {

          requestToken=twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);

          launchLoginWebView(requestToken);

          requestToken = null;

          }

          catch (TwitterException e)

          {

          System.out.println(e.getMessage());

          }

          }

          else

          {

          System.out.println(“Already Logged into twitter”);

          }

          }

          private void launchLoginWebView(RequestToken requestToken)

          {

          Intent intent = new Intent(MainActivity.this, LoginToTwitter.class);

          Log.d(“Authenticate URL”, requestToken.getAuthenticationURL());

          intent.putExtra(AUTHENTICATION_URL_KEY, requestToken.getAuthenticationURL());

          startActivityForResult(intent, LOGIN_TO_TWITTER_REQUEST);

          }

          @Override

          protected void onActivityResult(int requestCode, int resultCode, Intent data)

          {

          if (resultCode == Activity.RESULT_OK)

          {

          switch (requestCode)

          {

          case LOGIN_TO_TWITTER_REQUEST:

          try

          {

          if (!isTwitterAlreadyLogedin())

          {

          Uri uri = Uri.parse(data.getStringExtra(LoginToTwitter.CALLBACK_URL_KEY));

          System.out.println(“Uri — “+uri.toString());

          if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL))

          {

          // oAuth verifier

          String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

          System.out.println(“verifier”+verifier);

          new GetAccessToken().execute(verifier);

          }

          }
          }

          }

          catch (Exception e)

          {

          e.printStackTrace();

          }

          break;

          default:

          break;

          }

          }

          class GetAccessToken extends AsyncTask

          {

          ProgressDialog pdialog;

          String username ;

          @Override

          protected void onPreExecute()

          {

          pdialog = new ProgressDialog(MainActivity.this);

          pdialog.setMessage(“Please wait…”);

          pdialog.setCancelable(false);

          pdialog.show();

          super.onPreExecute();

          }

          @Override

          protected Long doInBackground(String… params)

          {

          String verifier=params[0];

          long userID = 0;

          try

          {

          // Get the access token

          accessToken = twitter.getOAuthAccessToken(verifier);

          try

          {

          username = twitter.getScreenName();

          }

          catch (Exception e)

          {

          e.printStackTrace();

          }

          // Shared Preferences

          Editor e = mSharedPreferences.edit();

          // After getting access token, access token secret

          // store them in application preferences

          e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());

          e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());

          // Store login status – true

          e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);

          e.putString(PREF_KEY_USER_NAME, username);

          e.commit(); // save changes

          userID = accessToken.getUserId();

          Log.v(“Twitter accessToken “, “> ” + accessToken.getToken());

          Log.v(“Twitter Secret Token “, “> ” + accessToken.getTokenSecret());

          Log.v(“UserName “, “> ” + username);

          Log.v(“UserID “, “> ” + userID);

          }

          catch (Exception e)

          {

          Log.e(“Twitter Login Error”, “> ” + e.getMessage());

          }

          return userID;

          }

          @Override

          protected void onPostExecute(Long result)

          {

          if (pdialog != null)

          {

          if (pdialog.isShowing())

          {

          // Hide login button and updating Ui

          updateUI();

          pdialog.dismiss();

          }

          }

          super.onPostExecute(result);

          }

          }

          • INDIAN

            Until u get

            accessToken.getToken()
            accessToken.getTokenSecret()

            you are not done

  • Mitesh Shah

    static final String URL_TWITTER_AUTH = “auth_url”;

    static final String URL_TWITTER_OAUTH_VERIFIER = “oauth_verifier”;

    static final String URL_TWITTER_OAUTH_TOKEN = “oauth_token”;

    What to write in above 3 variables..?? Application is crashing.. 🙁
    Please reply soon..

    • Kanguru

      I have same question with you

  • bhavani

    Hi Ravi, i am new to Android development and was following your tutorials to understand few of the functionalities I was planning to implement in my application. I must say, you are doing a wonderful job and all your tutorials are really awesome !! Thank you for sharing such wonderful tutorials..

    When you get a chance can you post a tutorial for Youtube integration with Android ? I have tried several ways and googled for good tutorials but couldnt find any..I tried Youtube API V3 as well as Android Youtube API.. I m having a hard time getting it to work. I just need to get a playlist of youtube videos for the youtube account credentials i supply . Can you please post something related to this ? Thanks so much.

  • Zem

    Any really working and less buggy code ? It would help us a lot.

  • Zem

    I already used the recommendations in disqus like put the loginToTwitter() method in AsyncTask, also I’ve tried the dirty way to bypass the Network on Main Thread Error like :

    if android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }

    and changing the targetSdk version to 9.

    , but still no luck

  • tiendh

    Great tutorial, but code has bugs needed to fix.
    For example:
    Thread thread = new Thread(new Runnable(){
    @Override
    public void run() {
    try {
    //Your code goes here
    loginToTwitter();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    });
    thread.start();

    And code to get access token also needs a thread.

  • Hemanth Dvshkk

    oauth //t4jsample? aauth_token might be temporarily down or it may have moved perminantly
    I got this message after click on Authorize app. Please help me about this

  • Hemanth Dvshkk

    If i click on login button ….. the page not going any where …
    plz help me

    • Guest

      hi… do replace twitter4j-core library with new twitter4j library (add all the libraries). Only this and the code will work.

  • Sheldon

    Sadly this is the first project from androidhive that has refused to run. Im getting a 401 error.

  • Sahitya Kumar Suman

    Those who are facing problem with this code ……. Listen is

    Code is completely fine but just need to add some few lines in MainActivity.java in onCreate() method

    just after the setContentView(….);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    After adding this line just go on link http://twitter4j.org/en/index.html and download the latest twitter java library class and replace with the library file given by th Ravi Sir in the above code ……….

    After doing so , Change the Project buil with minimum 17 or 18 Api by Clicking Righclick on your project into the Eclipse Project view — Properties — Android — Change build Api and Press Ok …….

    After doing so you will remove some error on those lines you added in the onCreate method ….. just remove those errors by giving

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)

    @SuppressLint(“NewApi”)

    above the onCreate() and after that Run your app in emulator and if Show some error like Twitter is not authentacating something like this then wait for some time like 2 hour and run it again …… You will be succesfully run your app ………

    I also faced many problems but now my App is Running fine and its Good …………..

  • Sahitya Kumar Suman

    Dear Sir @ravi8x:disqus

    Your code is working very fine for me and implemented more than 4 or 5 times in different apps but now I have a small problem ….. I just want the user when he authenticate the app on twitter then another activity should be opened which contain user name or other details … but this code open the main activity after the authentication by user so please help me ………….. really thankful to get your reply ….

    • Muiruri Gachanja

      @sahityakumarsuman:disqus
      @ravi8x:disqus
      my application has an error when i click on the ‘Login Button’ it gives me Browser Options on which it should Open the Twitter Handle on the call-back Url..
      HELP!!!!!

  • D

    Dear sir,
    Can you tell me, logout code for logout user from the twitter in the browser??
    I need that code to make another user can login in the app.
    Thank you sir.

  • Mainak devsinha

    This Toutorial is having some error. Like—->
    04-30 17:58:05.189: E/AndroidRuntime(2167): FATAL EXCEPTION: main

    04-30 17:58:05.189: E/AndroidRuntime(2167): android.os.NetworkOnMainThreadException

    04-30 17:58:05.189: E/AndroidRuntime(2167): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at java.net.InetAddress.getAllByName(InetAddress.java:220)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpConnection.(HttpConnection.java:71)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpConnection.(HttpConnection.java:50)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at com.androidhive.twitterconnect.MainActivity.loginToTwitter(MainActivity.java:236)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at com.androidhive.twitterconnect.MainActivity.access$1(MainActivity.java:223)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at com.androidhive.twitterconnect.MainActivity$1.onClick(MainActivity.java:123)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at android.view.View.performClick(View.java:3571)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at android.view.View$PerformClick.run(View.java:14247)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at android.os.Handler.handleCallback(Handler.java:605)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at android.os.Handler.dispatchMessage(Handler.java:92)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at android.os.Looper.loop(Looper.java:137)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at android.app.ActivityThread.main(ActivityThread.java:4517)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at java.lang.reflect.Method.invokeNative(Native Method)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at java.lang.reflect.Method.invoke(Method.java:511)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)

    04-30 17:58:05.189: E/AndroidRuntime(2167): at dalvik.system.NativeStart.main(Native Method)

  • Emma

    please sir hw do i get the user s email adress??

  • Hari Krishnan

    i need help sir … is it possible to twitter login through mobile app

  • rakesh kushwaha

    hello sir,can we check that our “MyTwitterApp” automatically login after Twitter(orignal App) login

    plz reply

  • No Namez

    Your tutorial is shit, it doesn’t build or even run. You irresponsible hack.

    • Sarbjot Singh

      AndroidHive is the best tutorial site for learning, you can not comments these type of comments for some one

      • Haha .. don’t worry Sarbjot.

        Thanks for support AH.

  • Alice John

    i am get the null uri Uri uri = getIntent().getData();//it is returning null….

    I have writen the login code inside the asynctask doInBackground method and the following code

    if (!isTwitterLoggedInAlready()) {

    Uri uri = getIntent().getData();

    if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {

    // oAuth verifier

    String verifier = uri

    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

    try {

    // Get the access token

    AccessToken accessToken = twitter.getOAuthAccessToken(

    requestToken, verifier);

    // Shared Preferences

    Editor e = mSharedPreferences.edit();

    // After getting access token, access token secret

    // store them in application preferences

    e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());

    e.putString(PREF_KEY_OAUTH_SECRET,

    accessToken.getTokenSecret());

    // Store login status – true

    e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);

    e.commit(); // save changes

    Log.e(“Twitter OAuth Token”, “> ” + accessToken.getToken());

    // Hide login button

    btnLoginTwitter.setVisibility(View.GONE);

    // Show Update Twitter

    lblUpdate.setVisibility(View.VISIBLE);

    txtUpdate.setVisibility(View.VISIBLE);

    btnUpdateStatus.setVisibility(View.VISIBLE);

    btnLogoutTwitter.setVisibility(View.VISIBLE);

    // Getting user details from twitter

    // For now i am getting his name only

    long userID = accessToken.getUserId();

    User user = twitter.showUser(userID);

    String username = user.getName();

    // Displaying in xml ui

    lblUserName.setText(Html.fromHtml(“Welcome ” + username + ““));

    } catch (Exception e) {

    // Check log for login errors

    Log.e(“Twitter Login Error”, “> ” + e.getMessage());

    }

    }

    }

    inside the OnPostExecute method but the uri is returning null and OnActivityResult() Function is not called………

    Plz help me in solving the issue

  • Muhammad Adil

    what is ConfigurationBuilder class ? I have used

    compile(‘com.twitter.sdk.android:twitter:1.5.1@aar’) {

    transitive = true

    }

    and could not find any class.

  • Wetcha Chaima

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
    builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
    Configuration configuration = builder.build();
    TwitterFactory factory = new TwitterFactory(configuration);
    twitter = factory.getInstance();

    it always show me the same error :Caused by: java.lang.NoClassDefFoundError: twitter4j.conf.PropertyConfiguration:

  • sanjeev

    Hi, How to login my application through twitter mobile application?when i integrate twitter i am able to login with browser succussfully?but how can i login with twitter mobile app?its urgent just give me the solution

  • abdul rehman

    ow to get user email address from twitter, i serached a lot but didnt get any solution ??please help

  • MinaSedrak

    Hey i am using Android Studio it gives NetworkOnMainThreadException by clicking on Login Button and fire loginToTwitter() function , Any Suggest Thanks ?

  • Vishal M. Vekariya

    TWITTER_CALLBACK_URL replace with my URL but app is stop with error

    08-20 12:37:22.752: E/AndroidRuntime(8067): android.os.NetworkOnMainThreadException
    08-20 12:37:22.752: E/AndroidRuntime(8067): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at java.net.InetAddress.getAllByName(InetAddress.java:215)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:370)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:221)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.androidhive.twitterconnect.MainActivity.loginToTwitter(MainActivity.java:236)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.androidhive.twitterconnect.MainActivity.access$1(MainActivity.java:223)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.androidhive.twitterconnect.MainActivity$1.onClick(MainActivity.java:123)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at android.view.View.performClick(View.java:5052)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at android.view.View$PerformClick.run(View.java:20162)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at android.os.Handler.handleCallback(Handler.java:739)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at android.os.Handler.dispatchMessage(Handler.java:95)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at android.os.Looper.loop(Looper.java:135)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at android.app.ActivityThread.main(ActivityThread.java:5753)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at java.lang.reflect.Method.invoke(Native Method)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at java.lang.reflect.Method.invoke(Method.java:372)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
    08-20 12:37:22.752: E/AndroidRuntime(8067): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

  • Vineet Kumar Saini

    What is this ??? Code is not working properly. Please update your code…………….

  • asep hidayat

    i get error
    java.lang.IllegalStateException: OAuth consumer key/secret combination not supplied

    on code
    requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);

    Any Suggest Thanks ?

    • Check twitter docs for latest updated one.

  • raja

    hi ravi, can twitter4j be used to upload videos to twitter? if yes then can you please share link to some resources which i can refer to as example?

  • manish

    Sir can you tell me how to integrate twitter using fabric.user should be
    able to login if twitter app is present and if twitter app is not
    present then he should able to login through the web activity

  • Manish Pal

    How can i tweet directly for my app to twitter using fabric.

  • Ashish Saini

    sir help me in my code authorize fail showing in loging with twitter

  • ankit

    sir
    please hep me how to get a token in android