Home > OAuth Signpost > A 30 minute guide to integrating Twitter in your Android application.

A 30 minute guide to integrating Twitter in your Android application.


Important note : As an update to this article, I’ve prepared a new post entitled Improved Twitter OAuth for Android focussing on a more simple Oauth / Android experience, and using the Google APIs Client Library for Java.


The goal of this article is to get twitter integration up & running from your Android app in 30 minutes. The guide will show you how to

  • setup a twitter test account
  • register a twitter application
  • authenticate the user in your Android application.
  • have the user send tweets from your Android application.

This guide is accompanied  by a sample application that’s available in Github in the AndroidTwitterSample repository. To import this project in Eclipse, I suggest using the EGit plugin that can be installed via the Main P2 Repository located at http://download.eclipse.org/egit/updates.

Before running this project, make sure you change the com.ecs.android.sample.twitter.Constants file to include your consumer key and consumer secret. (see subsequent section).
Once you have sample application up & running, you can copy the relevant classes into your projects to have Twitter up & running.

Twitter uses the OAuth protocol to authorize your android application to send tweets on behalf of the end-user. The end-user will need to authenticate against Twitter (meaning that your application will not capture the twitter username / password). Once the user has authorized access, you’ll be able to send tweets on behalf of the user. We’ll use signpost library to handle the OAuth communication, and the Twitter4J library to handle the Twitter specific interactions (sending tweets).

Setting up the Twitter account and application.

We’ll start by setting up a test-account on Twitter that we’ll use in our Android application. Goto the Twitter signup page and create an account. You’ll receive an  email from Twitter to confirm your account. You can skip the friends import as it will only be used for testing purposes.

Twitter Signup Page

Now that we have the Twitter account setup, we need to define an application. Go to the Twitter Application Registration page, and register an application. The application that your register here is required to perform Twitter interaction from your Android application. The Twitter application will have a consumer key and consumer secret associated with it that we’ll use in our Android application.

Fill in the required fields like you can see in the screenshot below :

Register an app at twitter

Once the application is registered, you’ll receive the following information associated with your application :

Consumer key

************************ (masked)

Consumer secret
************************ (masked)

Request token URL

https://api.twitter.com/oauth/request_token

Access token URL

https://api.twitter.com/oauth/access_token

Authorize URL

https://api.twitter.com/oauth/authorize

Registered OAuth Callback URL

http://someurl.com

This is all the information we need to start integrating Twitter in our Android application.
Note : The callback URL specified here is just a required field that we need to fill in, but is not used in our application. Instead, we define our own callback URL that we’ll pass on when authenticating the user

The sample application

The sample application is available in Github in the AndroidTwitterSample repository. Before running this project, make sure you change the com.ecs.android.sample.twitter.Constants file to include your consumer key and consumer secret. The application provides you with an end-to-end example on how to authenticate against Twitter and send tweets on behalf or the authenticated user.

The sample project has a dependency towards the following libraries :

  • signpost-commonshttp4-1.2.1.1.jar
  • signpost-core-1.2.1.1.jar
  • httpclient-4.0.1.jar
  • twitter4j-core-2.1.11

Dev note : You’ll need to include these libraries into your own project if you want to enable the Twitter integration.

The sample application contains 1 main activity with

  • a status message, indicating if you’re logged into Twitter.
  • a Tweet button, used to send a Tweet. When not authenticated, the application will redirect you to the Twitter loging page.
  • a Clear Credentials button, removing all saved credentials, forcing you to login next time you want to send a Tweet.

AndroidTwitterSample main activity

The Constants file

The Android project contains a Constants file containing the following information we received from Twitter when we setup our application.

public class Constants {

	public static final String CONSUMER_KEY = "<FILL IN YOUR CONSUMER KEY FROM TWITTER HERE>";
	public static final String CONSUMER_SECRET= "<FILL IN YOUR CONSUMER SECRET FROM TWITTER HERE>";

	public static final String REQUEST_URL = "http://api.twitter.com/oauth/request_token";
	public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
	public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";

	final public static String	CALLBACK_SCHEME = "x-latify-oauth-twitter";
	final public static String	CALLBACK_URL = CALLBACK_SCHEME + "://callback";

}

Dev note : If you want to integrate Twitter in your own app, I suggest making similar Constants available throughout your application.

What we have defined in the Constants class :

CONSUMER_KEY A key used when communicating with Twitter. This unique key is tied to the application we defined at Twitter that will be used by our Android app. The name of the application will be shown to the user when he authenticates against Twitter. This key is provided to you after registering an application at Twitter.
CONSUMER_SECRET The secret associated with the unique key. Think if this as a password where the key is a username. This key is provided to you after registering an application at Twitter.
REQUEST_URL URL needed to retrieve a request token. Part of the OAuth spec. This URL is provided to you after registering an application at Twitter.
AUTHORIZE_URL URL needed to authorize the application access to Twitter. Part of the OAuth spec. This URL is provided to you after registering an application at Twitter.
ACCESS_URL URL needed to retrieve an access token. Part of the OAuth spec. This URL is provided to you after registering an application at Twitter.
CALLBACK SCHEME A unique identifier within our Android app that we’ll use as a callback to retrieve the access token. This scheme can be freely choosen, but should be fairly unique to your application. We’ll use x-sample-oauth-twitter here.
CALLBACK_URL The redirect URL that Twitter will use after the user has authorized the request. When Twitter redirects to this URL, our Android application will take over to retireve the access token embedded in this URL.

The tweet button

The code behind the Tweet button is implemented  like this :

        tweet.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if (TwitterUtils.isAuthenticated(prefs)) {
            		sendTweet();
            	} else {
    				Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
    				i.putExtra("tweet_msg",getTweetMsg());
    				startActivity(i);
            	}
            }
        });

From a user experience, we opted to not have a seperate login button, but just have a single Tweet button, and encapsulate the authentication logic inside the Tweet login.
Basically, it performs a check to see if the user has already authenticated to Twitter.

  • If not, he’ll be redirected to the twitter login page by popping a browser. Once the user has authenticated, he’ll authorize the Android application to send tweets on the users behalf and the tweet will be sent (notice how we pass the tweet msg to the Intent when starting  the PrepareRequestTokenActivity activity).
  • If the user was already authenticated before, the tweet will be sent immediately.

Authenticating the user

We’ll start with the first case, where the user hasn’t authenticated to Twitter yet. This is the most complex part, as it involves implementing the OAuth flow to finally retrieve an access token.
This complete OAuth implementation is done in the OAuthRequestTokenTask and the PrepareRequestTokenActivity classes.

Before the user can authorize our application to send Tweets on his behalf, we’ll first need to redirect the user to the Twitter login page. This is done through the PrepareRequestTokenActivity. This will kick in the OAuth interactions required for your application to send tweets on behalf of the logged in user.

Dev note : I suggest copying these 2 classes into your own project, as they have been setup in a generic way.

The following table shows you in detail what each class does :

PrepareRequestTokenActivity Sets up the OAuth consumer and producer objects (Signpost library) and starts the asynchronous OAuthRequestTokenTask. Also handles the callback when the authentication is done to retrieve the access token.
OAuthRequestTokenTask Responsible for retrieving the request token, and popping a browser so that the user can authorizing our application to send Tweets on his behalf.
RetrieveAccessTokenTask Inner class in PrepareRequestTokenActivity. Triggered from the PrepareRequestTokenActivity onNewIntent method. After the user has logged in and authorized access, this task will retrieve the access token and store it in the shared preferences.

The PrepareRequestTokenActivity activity sets up our OAuth consumer and provider (using the Signpost library), and starts an Asynchronous task called OAuthRequestTokenTask.

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
    	try {
    		this.consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
    	    this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
    	} catch (Exception e) {
    		Log.e(TAG, "Error creating consumer / provider",e);
		}

        Log.i(TAG, "Starting task to retrieve request token.");
		new OAuthRequestTokenTask(this,consumer,provider).execute();
	}

This asynchronous task just starts an Intent that launches a browser to authenticate the user against Twitter. At this point, our Android application gives control to Twitter. The user enters his username/password, and Twitter will do the authentication. Notice how we also specify a callback URL. Twitter will redirect to this callback URL after the user has properly authenticated against twitter. In our case, the callback URL is x-oauthflow-twitter://callback. This callback is required to give back the control to our Android application.

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

		try {
			Log.i(TAG, "Retrieving request token from Google servers");
			final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
			Log.i(TAG, "Popping a browser with the authorize URL : " + url);
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
			context.startActivity(intent);
		} catch (Exception e) {
			Log.e(TAG, "Error during OAUth retrieve request token", e);
		}

		return null;
	}

The twitter login page

Twitter login page

In our AndroidManifest.xml, The PrepareRequestTokenActivity, responsible for popping the browser has an intent filter defined with a scheme and host that corresponds to our callback.

		<activity android:name=".PrepareRequestTokenActivity" android:launchMode="singleTask">>
			<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="x-oauthflow-twitter" android:host="callback" />
			</intent-filter>
		</activity>

Dev note : You’ll need to include this activity into your own project if you want to enable the Twitter integration.

Due to the fact that we have the intent filter defined we’ll be able to intercept the callback that Twitters sends. So after the user authenticated, Twitter sends a redirect to our callback URL, causing our onNewIntent method to kick in. At this point, we can continue with the OAuth flow and retrieve the access token using the RetrieveAccessTokenTask.

	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Uri uri = intent.getData();
		if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
			Log.i(TAG, "Callback received : " + uri);
			Log.i(TAG, "Retrieving Access Token");
			new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
			finish();
		}
	}

The RetrieveAccessTokenTask is responsible for capuring the access token, required to do communication with Twitter.
It basically extracts the access token from the callback URL, passed on to it from the previous code snippet. We then store the access token and secret in our shared preferences, so that the user doesn’t need to login to Twitter again, not even after restarting the application.

		@Override
		protected Void doInBackground(Uri...params) {
			final Uri uri = params[0];
			final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

			try {
				provider.retrieveAccessToken(consumer, oauth_verifier);

				final Editor edit = prefs.edit();
				edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
				edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
				edit.commit();

				String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
				String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

				consumer.setTokenWithSecret(token, secret);
				context.startActivity(new Intent(context,AndroidTwitterSample.class));

				executeAfterAccessTokenRetrieval();

				Log.i(TAG, "OAuth - Access Token Retrieved");

			} catch (Exception e) {
				Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
			}

			return null;
		}

Notice the executeAfterAccessTokenRetrieval method, that will be executed after having retrieved the access token. We’ll use this hook to actually send the message now.
It basically extracts the tweet message from the Intent that was passed along in the beginning of the OAuth flow (when clicking the Tweet button).

		private void executeAfterAccessTokenRetrieval() {
			String msg = getIntent().getExtras().getString("tweet_msg");
			try {
				TwitterUtils.sendTweet(prefs, msg);
			} catch (Exception e) {
				Log.e(TAG, "OAuth - Error sending to Twitter", e);
			}
		}

Sending the Tweet

Sending the actual Tweet is via a background thread like this :

	public void sendTweet() {
		Thread t = new Thread() {
	        public void run() {

	        	try {
	        		TwitterUtils.sendTweet(prefs,getTweetMsg());
	        		mTwitterHandler.post(mUpdateTwitterNotification);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
	        }

	    };
	    t.start();
	}

In order to provide feedback to the user (Toast message), we perform a post to a handler defined in our main Activity.

	private final Handler mTwitterHandler = new Handler();

    final Runnable mUpdateTwitterNotification = new Runnable() {
        public void run() {
        	Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
        }
    };

The actual sending of the Tweet is done through the Twitter4J library, where we retrieve the access token and secret. We set the consumer key, consumer secret and access token on our Twitter object, and call the updateStatus method to send our Tweet.

	public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
		String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
		String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

		AccessToken a = new AccessToken(token,secret);
		Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
		twitter.setOAuthAccessToken(a);
        twitter.updateStatus(msg);
	}

After making this call, your Tweet will be visible on your Twitter page :

Tweet on Twitter page

References

Bookmark and Share
Categories: OAuth Signpost Tags: , , ,
  1. Karthikeyan
    February 16th, 2011 at 20:46 | #1

    Nice Tutorial …Thanks

  2. February 18th, 2011 at 20:05 | #2

    Hi I am getting Request token or token secret not set in server reply error find the complete stack trace below

    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): Error during OAUth retrieve request token
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: The target server failed to respond
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:55)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:1)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at android.os.AsyncTask$2.call(AsyncTask.java:185)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at java.util.concurrent.FutureTask.run(FutureTask.java:122)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at java.lang.Thread.run(Thread.java:1060)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): Caused by: org.apache.http.NoHttpResponseException: The target server failed to respond
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:85)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:179)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:410)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at oauth.signpost.commonshttp.CommonsHttpOAuthProvider.sendRequest(CommonsHttpOAuthProvider.java:64)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:177)
    02-19 01:33:47.951: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(218): … 9 more

    • admin
      February 19th, 2011 at 09:19 | #3

      The stacktrace seems to indicate a network connectivity issue. NoHttpResponseException indicates that the target server (Twitter) failed to respond with a valid HTTP response.

  3. February 19th, 2011 at 21:20 | #4

    02-20 02:47:54.742: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(338): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: api.twitter.com

    hi changed my n/w and now i am doing it without any proxy connection but i am getting the above error

  4. admin
    February 22nd, 2011 at 16:29 | #5

    @Pranay airan Anything more in the stacktrace ? If you’re running this from an actual phone, make sure your time settings are correct (timezone). OAuth implementers check a timestamp that is sent by the client in order to validate the request. Google for example returns OAuthCommunicationException: Communication with the service provider failed: Service provider responded in error: 400 (Bad Request) when an invalid timestamp is sent.

  5. ol0
    February 23rd, 2011 at 15:36 | #6

    Hello,
    Thanks a lot for Your sample – it worked for me!
    @Pranay airan: maybe try to reinstall the app and clear browser cache (it never hurts) – I think it helped me once.

    I am now trying to improve responsiveness of this sample app – after you press “Tweet” for the first time it sometimes takes a few seconds (on the device) until browser appears and it blocks the UI. It would be nice to add a progress bar in between and launch everything in a new thread to avoid ANR.
    The second thing that could be improved is the black background visible for a while after PrepareRequestTokenActivity is started – it is also visible if you press “back” in the browser. So if user changes his mind he has two press “back” two times to really come back to the main application (the one with buttons).
    I will think of something but maybe You have some suggestions?

    Once again thanks

  6. March 18th, 2011 at 06:35 | #7

    Hey I am getting:

    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): FATAL EXCEPTION: main
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): android.os.NetworkOnMainThreadException
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.net.InetAddress.lookupHostByName(InetAddress.java:481)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:281)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.net.InetAddress.getAllByName(InetAddress.java:249)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:69)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:48)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1038)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:736)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpResponseImpl.(HttpResponseImpl.java:45)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:178)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:75)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:103)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.Twitter.getAccountSettings(Twitter.java:1440)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.lightsandshapes.papertwitter.TwitterUtils.isAuthenticated(TwitterUtils.java:23)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.lightsandshapes.papertwitter.StatusActivity.onClick(StatusActivity.java:51)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.view.View.performClick(View.java:3100)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.view.View$PerformClick.run(View.java:11644)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.Handler.handleCallback(Handler.java:587)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.Handler.dispatchMessage(Handler.java:92)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.Looper.loop(Looper.java:126)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.app.ActivityThread.main(ActivityThread.java:3997)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.lang.reflect.Method.invokeNative(Native Method)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.lang.reflect.Method.invoke(Method.java:491)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at dalvik.system.NativeStart.main(Native Method)

    it dies at
    try {
    twitter.getAccountSettings();
    return true;
    } catch (TwitterException e) {
    return false;
    }

    for some reason getAccountSettings() crashes the program.
    However I can return false, get the token then return true and reinstall the app and post with it.

    Any ideas?

  7. chamith
    March 18th, 2011 at 09:44 | #9

    Hi,

    This didn’t work. I evan touch your code. only import your project. but when I twitt it shows only black screen.

    thanks.

  8. admin
    March 20th, 2011 at 20:10 | #10

    @chamith
    You should see some kind of stack trace in your eclipse DDMS perspective. Please post it so I can have a look. Code works fine here out of the box (Android 2.1 / 2.2)

  9. Beege
    March 22nd, 2011 at 02:26 | #11

    Excellent guide and code. With just the changes for package path and my consumer key and secret, it ran without a hitch. VERY appreciated!

  10. surya
    March 22nd, 2011 at 17:27 | #12

    I imported the file and made changes for package etc, but how should I INTEGRATE this file, such that it gets embedded into my Android Application??

  11. David C
    March 29th, 2011 at 18:53 | #13

    HI,

    Downloaded the app (kind of understand it!)

    Added in the two keys – open app and when I click on the Tweet button it doesn’t open the browser and just hangs on a black screen?

    Any help would be great!

    David

  12. April 4th, 2011 at 13:53 | #14

    Hanged on a black screen too.

  13. Rajani
    April 6th, 2011 at 05:08 | #15

    Hi,
    I have registered my app and using the generated CONSUMER KEY and CONSUMER SECRET but I am getting

    05-06 04:57:48.835: INFO/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): Retrieving request token from Google servers
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): Error during OAUth retrieve request token
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: api.twitter.com
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:55)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:1)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at android.os.AsyncTask$2.call(AsyncTask.java:185)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.lang.Thread.run(Thread.java:1096)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): Caused by: java.net.UnknownHostException: api.twitter.com
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.net.InetAddress.lookupHostByName(InetAddress.java:504)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:278)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at java.net.InetAddress.getAllByName(InetAddress.java:242)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at oauth.signpost.commonshttp.CommonsHttpOAuthProvider.sendRequest(CommonsHttpOAuthProvider.java:64)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:177)
    05-06 04:57:49.318: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): … 9 more

    What we have to give in call back url field while registering an app with our twitter account.

  14. rajani
    April 7th, 2011 at 06:36 | #16

    @Mike Z
    Hey ,

    Mike Z :
    Hey I am getting:
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): FATAL EXCEPTION: main
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): android.os.NetworkOnMainThreadException
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.net.InetAddress.lookupHostByName(InetAddress.java:481)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:281)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.net.InetAddress.getAllByName(InetAddress.java:249)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:69)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:48)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1038)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:736)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpResponseImpl.(HttpResponseImpl.java:45)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:178)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:75)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:103)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at twitter4j.Twitter.getAccountSettings(Twitter.java:1440)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.lightsandshapes.papertwitter.TwitterUtils.isAuthenticated(TwitterUtils.java:23)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.lightsandshapes.papertwitter.StatusActivity.onClick(StatusActivity.java:51)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.view.View.performClick(View.java:3100)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.view.View$PerformClick.run(View.java:11644)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.Handler.handleCallback(Handler.java:587)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.Handler.dispatchMessage(Handler.java:92)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.os.Looper.loop(Looper.java:126)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at android.app.ActivityThread.main(ActivityThread.java:3997)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.lang.reflect.Method.invokeNative(Native Method)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at java.lang.reflect.Method.invoke(Method.java:491)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
    03-18 02:29:42.310: ERROR/AndroidRuntime(12287): at dalvik.system.NativeStart.main(Native Method)
    it dies at
    try {
    twitter.getAccountSettings();
    return true;
    } catch (TwitterException e) {
    return false;
    }
    for some reason getAccountSettings() crashes the program.
    However I can return false, get the token then return true and reinstall the app and post with it.
    Any ideas?

  15. rajani
    April 7th, 2011 at 06:38 | #17

    Hey,

    I’m getting the same problem. i’m working on Android 2.2 (Froyo). if you got any solution please give the reply.

  16. Sunil David
    April 19th, 2011 at 06:09 | #18

    Nice Work it helped me a lot!!! Thank U

  17. Jahnavi Athuluru
    April 21st, 2011 at 08:41 | #19

    Hi,

    I am also getting black screen.
    I see in the above comments, that few others have faced the same problem, but anyone got a solution for this.

  18. Jahnavi Athuluru
    April 21st, 2011 at 19:19 | #20

    @David C
    Hi David, and Mamaun,

    Did you overcome the black screen. I donno where i am going wrong. but still facing that problem.

    Can anyone please suggest me what to change.

    Thanks,

  19. Jahnavi Athuluru
    April 21st, 2011 at 19:19 | #21

    @Mamaun

    Hi David, and Mamaun,

    Did you overcome the black screen. I donno where i am going wrong. but still facing that problem.

    Can anyone please suggest me what to change.

    Thanks,

  20. April 24th, 2011 at 09:48 | #22

    Hi,
    I’ve copied exactly from twitter consumer secret and consumer key but get the message “Logged into Twitter: false”. I can’t Figure out where the problem is. I get the following message:

    Authentication error: Unable to respond to any of these challenges: {oauth=WWW-Authenticate: OAuth realm=”http://twitter.com”}

    ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): Error during OAUth retrieve request token

    ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(371): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.

    Appreciate any help

  21. Alex
    April 26th, 2011 at 13:58 | #23

    Hi all,
    I’m facing the same issue described here above: black screen and CommunicationException raised. I put all the permissions needed, so… I really don’t know what I’m missing.

    Anyone could help me?

  22. May 3rd, 2011 at 21:54 | #24

    @Alex

    Make sure that your application type is configured under Twitter as browser (you’ll need to fill in the callback URL otherwise it won’t be saved).

  23. michal
    May 9th, 2011 at 19:59 | #25

    Hi
    Is there way to login without pop up web browser?

  24. Jorrit
    May 10th, 2011 at 08:53 | #26

    I am getting this error:
    oauth.signpost.exception.OAuthExpectationFailedException: Authorized request token or token secret not set. Did you retrieve an authorized request token before?

    Anybody knows what is going wrong? I took the source from github and changed the consumerkey and consumersecret with the one I got from Twitter.

  25. Dane
    May 17th, 2011 at 04:42 | #27

    I’m also getting the black screen. Can somebody help me? Thank you!

  26. Sam
    June 8th, 2011 at 14:19 | #28

    Hi
    I am unable to tweet, with following error trace

    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): Error during OAUth retrieve request token
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:239)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:55)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:1)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at android.os.AsyncTask$2.call(AsyncTask.java:185)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at java.util.concurrent.FutureTask.run(FutureTask.java:122)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
    06-08 19:11:05.733: ERROR/com.ecs.android.sample.twitter.OAuthRequestTokenTask(535): at java.lang.Thread.run(Thread.java:1060)

    Any help or clue will be highly appreciated!

  27. June 22nd, 2011 at 11:30 | #29

    Hi,
    Its an awesome tutorial. Its working fine.

    But, if after logged in and authorized the app and if press “Clear Crendentials”, its actually clearing the Shared Preferences. and now user needs to log-in again so twitter login page should be displayed, not the Authorize app page, so what should i do to open Twitter Login page instead of Authorize app (if i have already authorized the app once), is it the case ?

  28. NITIN
    August 24th, 2011 at 05:45 | #30

    Working awesomely !!

  29. Tanja
    September 7th, 2011 at 19:41 | #31

    Thanks, was about to start pulling my hair out, tried like 60 examples ;)

  30. Akshay
    September 12th, 2011 at 14:43 | #32

    Hi,
    Thanks for such a nice tutorial.It works perfectly.

  31. rahu
    September 14th, 2011 at 12:27 | #33

    Hi,
    Thanks for the post, I can now post tweets ..but can I show the tweet before posting it using the twitter4j…in some dialogue window just like we did for login..?

  32. NITIN
    October 3rd, 2011 at 12:34 | #34

    when i integrate this with any application error is coming !!

    10-03 17:09:12.545: ERROR/dalvikvm(1273): Could not find class ‘twitter4j.http.AccessToken’, referenced from method com.jcp.dp.android.twitter.TwitterUtils.isAuthenticated

    10-03 17:09:12.545: WARN/dalvikvm(1273): VFY: unable to resolve new-instance 1103 (Ltwitter4j/http/AccessToken;) in Lcom/jcp/dp/android/twitter/TwitterUtils;

    10-03 17:09:12.545: DEBUG/dalvikvm(1273): VFY: replacing opcode 0×22 at 0×0017

    10-03 17:09:12.545: DEBUG/dalvikvm(1273): Making a copy of Lcom/jcp/dp/android/twitter/TwitterUtils;.isAuthenticated code (233 bytes)
    10-03 17:09:12.545: ERROR/dalvikvm(1273): Could not find class ‘twitter4j.http.AccessToken’, referenced from method com.jcp.dp.android.twitter.TwitterUtils.sendTweet

    10-03 17:09:12.545: WARN/dalvikvm(1273): VFY: unable to resolve new-instance 1103 (Ltwitter4j/http/AccessToken;) in Lcom/jcp/dp/android/twitter/TwitterUtils;

    10-03 17:09:12.545: DEBUG/dalvikvm(1273): VFY: replacing opcode 0×22 at 0×0010

    10-03 17:09:12.545: DEBUG/dalvikvm(1273): Making a copy of Lcom/jcp/dp/android/twitter/TwitterUtils;.sendTweet code (104 bytes)

    10-03 17:09:12.545: DEBUG/TAG19(1273): yes

    10-03 17:09:12.555: DEBUG/AndroidRuntime(1273): Shutting down VM

    10-03 17:09:12.555: WARN/dalvikvm(1273): threadid=3: thread exiting with uncaught exception (group=0x4001b188)

    10-03 17:09:12.555: ERROR/AndroidRuntime(1273): Uncaught handler: thread main exiting due to uncaught exception

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): java.lang.NoClassDefFoundError: twitter4j.http.AccessToken

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at com.jcp.dp.android.twitter.TwitterUtils.isAuthenticated(TwitterUtils.java:21)

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at
    com.jcp.dp.android.twitter.AndroidTwitterSample$1.onClick(AndroidTwitterSample.java:46)

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.View.performClick(View.java:2364)

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.View.onTouchEvent(View.java:4179)

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.widget.TextView.onTouchEvent(TextView.java:6540)

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.View.dispatchTouchEvent(View.java:3709)

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)

    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.os.Handler.dispatchMessage(Handler.java:99)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.os.Looper.loop(Looper.java:123)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at android.app.ActivityThread.main(ActivityThread.java:4363)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at java.lang.reflect.Method.invokeNative(Native Method)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at java.lang.reflect.Method.invoke(Method.java:521)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    10-03 17:09:12.564: ERROR/AndroidRuntime(1273): at dalvik.system.NativeStart.main(Native Method)

  33. manas
    October 15th, 2011 at 15:19 | #35

    hey guys try this link it seemed to be very beneficial for me http://learnandroidquick.blogspot.com/2011/10/working-example-to-deal-with-oauth-20.html

  34. deraga
    November 10th, 2011 at 10:19 | #36

    For everyone who’s getting a black screen, make sure your callback_url in your twitter app settings is the same as the callback_url in your android app source code. That solved the black screen for me. Hope this will help.

  35. Mohammad Umair Khan
    November 11th, 2011 at 15:43 | #37

    Hey

    I am getting this unusual message on the Logcat. Can you please have a look at this…

    11-11 20:41:08.304: D/dalvikvm(8527): GC_FOR_MALLOC freed <1K, 50% free 2989K/5959K, external 0K/0K, paused 16ms
    11-11 20:41:09.415: I/global(8527): Loaded time zone names for en_US in 649ms.
    11-11 20:41:09.435: W/DefaultRequestDirector(8527): Authentication error: Unable to respond to any of these challenges: {oauth=WWW-Authenticate: OAuth realm="https://api.twitter.com"}
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): Error during OAUth retrieve request token
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:239)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:55)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:1)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at android.os.AsyncTask$2.call(AsyncTask.java:185)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
    11-11 20:41:09.445: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(8527): at java.lang.Thread.run(Thread.java:1027)

    Thanks a Gazillion !!

  36. FoToKoTo
    November 14th, 2011 at 16:10 | #38

    I’m also getting the black screen.
    From what I can understand from the “LogCat” in eclispse (in OAuthRequestTokenTask class) throws exception

    try {
    Log.i(TAG, “Retrieving request token from Google servers”);
    final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);<–HERE
    Log.i(TAG, "Popping a browser with the authorize URL : " + url);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
    context.startActivity(intent);
    } catch (Exception e) {
    Log.e(TAG, "Error during OAUth retrieve request token", e);
    }

  37. Zhou
    November 29th, 2011 at 18:04 | #39

    Not working.

    11-30 01:02:40.398: W/DefaultRequestDirector(992): Authentication error: Unable to respond to any of these challenges: {oauth=WWW-Authenticate: OAuth realm=”http://api.twitter.com”}
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): Error during OAUth retrieve request token
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:239)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:55)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:1)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at android.os.AsyncTask$2.call(AsyncTask.java:185)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
    11-30 01:02:40.428: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(992): at java.lang.Thread.run(Thread.java:1019)

  38. abhinav
    December 1st, 2011 at 08:56 | #40

    Hi I am in need of piece of code that how to get twitter follower / friend list in android by using above sample

  39. Rizvan
    December 28th, 2011 at 07:26 | #41

    Hi ,
    Good application dude :) .Please help out with youtube integration in android application for uploading videos .

  40. Asif
    December 28th, 2011 at 21:11 | #42

    Wow what a great tutorial. I love it when people actually try to make you understand, versus the more common “ok step 1 step 2…”. Thank you!

  41. January 10th, 2012 at 21:13 | #43

    Thanks for this. I’m a noob trying to wrap my head sround this stuff. Why use this instead of AccountManager (http://developer.android.com/reference/android/accounts/AccountManager.html)?

  42. Abhinav
    April 3rd, 2012 at 08:19 | #44

    Could not find class ‘twitter4j.http.AccessToken’, referenced from method com.ecs.android.sample.twitter.TwitterUtils.isAuthenticated

    what this error is all the jars are already their in the project i just downloaded the code and entered the two consumer keys .?????

    twitter really sucks facebook was a lot easier

  43. Nitesh
  44. loola san
    April 13th, 2012 at 00:44 | #46

    @loola san
    go to https://dev.twitter.com
    then “settings”
    then fill the “Callback URL” with any dummy URL . it will solve the black screen guys . it works for me now .
    and , where i can make this tweet I am posting controlled by the user himself .
    it keep tweeting the same msg .

  45. aj_shehan
    April 16th, 2012 at 05:15 | #47

    @Abhinav

    Whats the Android API version u are using? I had the same problem since I was using API version 15 and solved by changing the name of the lib folder to libs. The added JAR files will be included in the Android Dependencies.

  46. aj_shehan
    April 16th, 2012 at 06:27 | #48

    I recreated this project in android API level 15, and the following methods return an empty string,

    String token = prefs.getString(OAuth.OAUTH_TOKEN, “”);
    String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET,”");

    the reset of the code has not been changed, it is exactly as given in the example.

    I would greatly appreciate your help in this, Thank You

  47. aj_shehan
    April 16th, 2012 at 07:06 | #49

    On searching more in the pref object OAuth.OAUTH_TOKEN and OAUTH_TOAKEN_SECRET are not available. can any one please provide a reason for this.

  48. ritesh
    April 16th, 2013 at 06:57 | #50

    NOT WORKING , AUTHORIZATION FAILED

    Authentication error: Unable to respond to any of these challenges: {oauth=www-authenticate: OAuth realm=”https://api.twitter.com”}
    04-16 12:24:29.554: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(20968): Error during OAUth retrieve request token
    04-16 12:24:29.554: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(20968): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.
    04-16 12:24:29.554: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(20968): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:239)
    04-16 12:24:29.554: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(20968): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    04-16 12:24:29.554: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(20968): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)

  49. Douglas Soares
    May 15th, 2013 at 19:31 | #51

    Hey evryone,
    I’m having some problems with twitter4j lib, if the sistem clock is wrong the requestToken() fail, is there someone that knows how to solve it? i’ve downloaded a twitter client end up test if the same ocours, but if change the date it still publish, I would like that my app do de same, since now i thank all of you that try help me.
    See ya.

  1. February 13th, 2011 at 20:30 | #1
  2. August 8th, 2011 at 20:52 | #2