How to Post Twitter Status from Android

While developing one of my Android application, i found it was hard to find a good and simple tutorial on how to integrate Twitter into Android app.  There are some external java libraries over the net that can be used to integrate Twitter into Android app, but they lack of good documentation and tutorial on how to use it on Android. So i  made my own implementation using  Twitter4j and oauth-signpost library. In this tutorial, i create one sample Android project to show how to connect to Twitter, save its token and username on shared preferences so it can be used later to post status to Twitter.

Update 13 Feb 2014:

Updated version of Android-Twitter library available on my new repo on Github, please use this new library for  compatibility with new Twitter REST API v.1.1

New Android-Twitter Library

===================================

I. Register Twitter Application

To enable user to post status to Twitter, first you have to create one Twitter application. Simply go to Twitter Apps page and register your application. Fill the ‘Application Name‘ with your desired name, it has to be unique. If you use a name that already exist (taken by someone), you’ll get a warning message.  On ‘Application Type’ option, choose ‘Browser’ , and because its a browser type application but used in mobile application, you can set it’s callback url on ‘Callback URL‘ field  with any url you want. On ‘Default Access type’, choose ‘Read and Write‘ to enable access to post status. Click save and if all things going well, you’ll get a page showing your consumer key and secret key. Copy these two keys for later use in Android app.

II. Android Integration

To integrate Twitter into Android app, you need four external jar files from two different libraries, Twitter4j and oauth-signpost. You can download latest version from Twitter4j download page or use the one included in my sample project (twitter4j-core-2.1.6.jar) and oauth-signpost from oauth-signpost download page (signpost-core-1.2.1.1.jar, signpost-commonshttp4-1.2.1.1.jar, signpost-jetty6-1.2.1.1.jar). Add the four external jars into your Android project (on Eclipse, right click on your project->properties then on Java Build Path click Add External JARs button to select files)

In my sample project, i create three helper classes (TwitterApp.java,  TwitterDialog.java, and TwitterSession.java) to handle authentication using Webview Dialog and session handler to save token and username on Shared Preferences.

Code implementation

1. Twitter Connection (TestConnection.java)

This example shows how to connect to Twitter, display webview dialog to authorize user then save user’s token and username on shared preference for later use.

public class TestConnect extends Activity {
	private TwitterApp mTwitter;
	private CheckBox mTwitterBtn;

	private static final String twitter_consumer_key = "xxx";
	private static final String twitter_secret_key = "xxx";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		mTwitterBtn	= (CheckBox) findViewById(R.id.twitterCheck);

		mTwitterBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onTwitterClick();
			}
		});

		mTwitter 	= new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

		mTwitter.setListener(mTwLoginDialogListener);

		if (mTwitter.hasAccessToken()) {
			mTwitterBtn.setChecked(true);

			String username = mTwitter.getUsername();
			username		= (username.equals("")) ? "Unknown" : username;

			mTwitterBtn.setText("  Twitter (" + username + ")");
			mTwitterBtn.setTextColor(Color.WHITE);
		}

		Button goBtn = (Button) findViewById(R.id.button1);

		goBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(TestConnect.this, TestPost.class));
			}
		});
	}

	private void onTwitterClick() {
		if (mTwitter.hasAccessToken()) {
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);

			builder.setMessage("Delete current Twitter connection?")
			       .setCancelable(false)
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   mTwitter.resetAccessToken();

			        	   mTwitterBtn.setChecked(false);
			        	   mTwitterBtn.setText("  Twitter (Not connected)");
			        	   mTwitterBtn.setTextColor(Color.GRAY);
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();

			                mTwitterBtn.setChecked(true);
			           }
			       });
			final AlertDialog alert = builder.create();

			alert.show();
		} else {
			mTwitterBtn.setChecked(false);

			mTwitter.authorize();
		}
	}

	private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
		@Override
		public void onComplete(String value) {
			String username = mTwitter.getUsername();
			username		= (username.equals("")) ? "No Name" : username;

			mTwitterBtn.setText("  Twitter  (" + username + ")");
			mTwitterBtn.setChecked(true);
			mTwitterBtn.setTextColor(Color.WHITE);

			Toast.makeText(TestConnect.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
		}

		@Override
		public void onError(String value) {
			mTwitterBtn.setChecked(false);

			Toast.makeText(TestConnect.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
		}
	};
}

First, create an instance of  TwiterApp class with context, consumer key and secret key as constructor’s parameters. Use hasAccessToken() method to check if there is previously saved session. If there is no saved session, call authorize() to open authorization dialog. If user allows the connection, his access token and user name will be saved on shared preferences. You can setup listener to handle on success and on error event by creating an instance of TwDialogListener and pass it to setListener() method.

2. Post Status (TestPost.java)

This example shows how to post Twitter status. If there is no previously saved session, display authorization dialog to allow user authorize the connection then post status using different thread.

public class TestPost extends Activity {
	private TwitterApp mTwitter;
	private CheckBox mTwitterBtn;
	private String username = "";
	private boolean postToTwitter = false;

	private static final String twitter_consumer_key = "xxxx";
	private static final String twitter_secret_key = "xxxx";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.post);

		Button postBtn 				= (Button) findViewById(R.id.button1);
		final EditText reviewEdit   = (EditText) findViewById(R.id.revieew);

		postBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String review = reviewEdit.getText().toString();

				if (review.equals("")) return;

				postReview(review);

				if (postToTwitter) postToTwitter(review);
			}
		});

		mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

		mTwitter.setListener(mTwLoginDialogListener);

		mTwitterBtn	= (CheckBox) findViewById(R.id.twitterCheck);

		mTwitterBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mTwitter.hasAccessToken()) {
					postToTwitter = mTwitterBtn.isChecked();
				} else {
					mTwitterBtn.setChecked(false);
					mTwitter.authorize();
				}
			}
		});

		if (mTwitter.hasAccessToken()) {
			username 	= mTwitter.getUsername();
			username	= (username.equals("")) ? "No Name" : username;

			mTwitterBtn.setText("  Twitter  (" + username + ")");
		}
	}

	private void postReview(String review) {
		//post to server

		Toast.makeText(this, "Review posted", Toast.LENGTH_SHORT).show();
	}

	private void postToTwitter(final String review) {
		new Thread() {
			@Override
			public void run() {
				int what = 0;

				try {
					mTwitter.updateStatus(review);
				} catch (Exception e) {
					what = 1;
				}

				mHandler.sendMessage(mHandler.obtainMessage(what));
			}
		}.start();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String text = (msg.what == 0) ? "Posted to Twitter" : "Post to Twitter failed";

			Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
		}
	};
	private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
		@Override
		public void onComplete(String value) {
			username 	= mTwitter.getUsername();
			username	= (username.equals("")) ? "No Name" : username;

			mTwitterBtn.setText("  Twitter  (" + username + ")");
			mTwitterBtn.setChecked(true);

			postToTwitter = true;

			Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
		}

		@Override
		public void onError(String value) {
			mTwitterBtn.setChecked(false);

			Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
		}
	};
}

Update 2011-10-01

- Fix authorization failed bug when attempt to authorize after logging out. This was caused by an exception (java.lang.IllegalStateException: consumer key/secret pair already set) was thrown by setOauthConsumer(consumerKey,secretKey) method of Twitter class. This method should be called once.

You can download  the source code here (with external jars) or via github here

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

  1. supertoonz says

    i cant connect twitter

    when i download yr app

    i add external jar then copy and replace
    my cunsumer key and consumer secret in yr app but when i run emulator and click
    checkbox to connect , app show “Twitter connection failed”
    because mTwitter.hasAccessToken() = false

    Login dilaog is not show

  2. Jahanzaib says

    i am also getting “Twitter connection failed” on device but its working correct on emualator. . . Can you tell me What the mistake i am doing ? ? ?

    Thanks in advance.

      • says

        Hi PvTai, on web settings, have set the ‘Application Type’ to browser? and also on TwitterApp.java, use ” public static final String CALLBACK_URL = “twitterapp://connect” ” instead of public static final String CALLBACK_URL = “http://twitter.com/#!/QGSVietnam”

        • PvTai says

          Ok, I have done. thanks.
          but I see you said “you can put any url as Callback URL.”
          So why now are you saying to use ” public static final String CALLBACK_URL = “twitterapp://connect” ” instead of public static final String CALLBACK_URL = “http://twitter.com/#!/QGSVietnam”. I really do not understand about this issue.
          You can say more to you, please.

  3. Deepa says

    Hi..
    Article is helpful to begineers like me but when i download ur app i hve error in TwitterApp.java in the CommonsHttpOAuthConsumer and OAuthProvider java class. it ask me to create new class with this name.. how to solve this problem?

  4. snowind says

    Hi, I have downloaded yr app and it works.

    Now I am trying to learn it and writing my app. While I have a question, why do u use Handler in TwitterApp.java? Why don’t u authorize directly?

    • snowind says

      I tried to use startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)) and onNewIntent(Intent) to get the verifier. But when I ran it on the TwitterApp.java, it turned out to be NullnotFound? Can you help me

  5. new_user says

    Hi,
    i solved the issue, i just commented these lines in Testost ie.,
    if (review.equals(“”)) return;
    postReview(review);
    if (postToTwitter) postToTwitter(review);

    and called postToTwitter instead,
    hope this helps sumbody,
    thanks

  6. says

    Hi i got this error:

    04-25 14:07:51.188: WARN/System.err(322): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Received authentication challenge is null

    Can you help me?
    Thanks

    • says

      You don’t have to signout, there is no session like facebook. Just delete the token using resetAccessToken method on TwitterApp.java

      • Naga Shankar says

        Hi Lorenz,

        This seems to be wrong. Because after i deleted the access token and restarted the application and again tryed to sign in, i still can see the user profile picture and “Signout” option in Twitter WebView Page(on top right corner). And in that web page there are no editfields to receive fresh username and password.

        I am guessing that Twitter Webpage has stored there credentials in it’s own shared preferences.

        How can we completely clear all login info so that it wont show those details again?

  7. says

    Hi,
    Thanks for providing the information. I tried working on it. When I connect it to the mobile phone. and Press the Tweet Post button, it does not initiate anything. as in No Response. And it is mentioned that the twitter account is also Not connected. the Callback Url is the new value only. It would be helpful of you.

  8. SEDHURAJA says

    Hey ppl , I m not able to debug !!! i m getting Twitter Connection Failed ! I changed callback url !!
    I m not getting the dialog box where we have to enter the username password . pls post any perfectly working code !!

      • Piyush says

        Hi, i am trying your code and i have consumer as well secret key but all the time i am getting System error oauth.singpost.exception.OAuhtCommunicationException: communication with the service provider failed: http//twitter.com/oaut/request_token, i tried to resolve it but i can’t figure it out.

  9. gianpaolo says

    hello!
    thank you very much for this article.

    I have 2 question:
    1)when “deny” is pressed, should the webview be dismissed or do I have to add some code?
    2)my boss wants me to write an application that can post on twitter without user interaction (I have login and password), but I dont think it is possible anymore, since now we have to deal with oauth. Am I right?

    regards

  10. Sameer says

    Hi everyone,
    I would like to close the authorize dialog box, when user clicks on “No Thanks.” How can I make it happen.

    thanks

    Sameer

  11. Nandagopal says

    Hi,

    I am trying to integrate the Twitter in to my App. I registered the app and got the consumer key as well as the secret key too. Whenever i tried to refer those in the code and execute the app, it gives me the following error.

    Seems like a some communication exception

    05-15 13:57:37.988: WARN/System.err(488): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://twitter.com/oauth/request_token
    05-15 13:57:37.988: WARN/System.err(488): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    05-15 13:57:37.998: WARN/System.err(488): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    05-15 13:57:37.998: WARN/System.err(488): at net.xxx.android.TwitterApp$2.run(TwitterApp.java:117)
    05-15 13:57:37.998: WARN/System.err(488): Caused by: java.io.FileNotFoundException: http://twitter.com/oauth/request_token
    05-15 13:57:38.007: WARN/System.err(488): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
    05-15 13:57:38.007: WARN/System.err(488): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18)
    05-15 13:57:38.017: WARN/System.err(488): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228)
    05-15 13:57:38.017: WARN/System.err(488): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    05-15 13:57:38.017: WARN/System.err(488): … 2 more

  12. gayathri says

    Hi,

    I am learning android from learning android book . Thanks for this wonderful post . Can i connect to twitter without registering my application , just by calling the twitter constructor and update status as i don’t have a url to register.

  13. sam says

    hi, when i try to authorize, dialog box does not open, instead i get twitter connection failed message. My callback url is “twitterapp://connect” . I changed DefaultOAuther to CommonsHttpOAuth .I cant figure out what i am doing wrong.

  14. sam says

    this is the logcat:

    05-24 17:28:03.838: WARN/DefaultRequestDirector(2359): Authentication error: Unable to respond to any of these challenges: {}

    05-24 17:28:03.838: INFO/global(2359): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.

    05-24 17:28:03.848: DEBUG/TwitterApp(2359): Failed to get request token

    05-24 17:28:03.848: WARN/System.err(2359): 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.

    05-24 17:28:03.848: WARN/System.err(2359): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:239)

    05-24 17:28:03.848: WARN/System.err(2359): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)

    05-24 17:28:03.848: WARN/System.err(2359): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)

    05-24 17:28:03.848: WARN/System.err(2359): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:118)

    05-24 17:28:03.868: DEBUG/SurfaceFlinger(109): Layer::setBuffers(this=0×857658), pid=2359, w=1, h=1

    05-24 17:28:03.868: DEBUG/SurfaceFlinger(109): Layer::setBuffers(this=0×857658), pid=2359, w=1, h=1

    05-24 17:28:03.868: WARN/InputManagerService(109): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@465751b8

    please note that the application is running fine on emulator. i get this exception when i try to run it on device. I tested it on HTC magic and HTC desire

  15. Ahmed El-Sharkasy says

    Thanks a lot for this beneficial tutorial.

    I have a problem that when the pin is displayed in the twitter web view , i am trapped and cant return to my application
    do i have to add something to get this working or am missing something here?

    waiting for your reply

  16. Karan says

    Hi lorenz ,
    I hace downloaded your application but whenever i run and click on twitter i get a toast twitter connection failed….please help guys

  17. says

    for all those who receive the 401 error: check if the time on the device is set correctly, otherwise it is impossible to receive the authentication for the fact that the validity has expired
    ;)

  18. Hauki says

    Hey, thanks for great tutorial. I have only changed DefaultOAuther to CommonsHttpOAuth and added my own keys. The problem is that t wont work on my device over wifi, but when going over 3G or on the emulator it works just fine.

    It just displays loding for a while after i’ve put in my mail and passwor, then it shows “Twitter connection failed”.

    Logcat:
    06-17 17:30:26.881: DEBUG/Twitter-WebView(1429): Loading URL: http://twitter.com/oauth/authorize

    06-17 17:30:39.643: DEBUG/dalvikvm(1429): GC_CONCURRENT freed 1052K, 50% free 3569K/7047K, external 2078K/2137K, paused 2ms+3ms

    06-17 17:30:39.647: DEBUG/webviewglue(1429): nativeDestroy view: 0x36b038

    06-17 17:30:49.815: DEBUG/Twitter-WebView(1429): Page error: The server failed to communicate. Try again later.

    06-17 17:30:49.842: DEBUG/Twitter-WebView(1429): Loading URL: http://twitter.com/oauth/authorize

  19. says

    hi, i cant seem to go past beyond this line

    authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);

    in TwitterApp

    it just hangs

  20. says

    looks promissing, must try. Actually i am surprised that there are no good samples how to do main operations with Twitter and Facebook …

  21. Maruba says

    Hey,
    i have a problem with your Source code, but i dont know how to fix it, can you help me please?

    i already tried it with ‘https://api.twitter.com’ instead of ‘http://twitter.com’ ang got the same result

    D/TwitterApp( 1337): Failed to get request token
    W/System.err( 1337): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://twitter.com/oauth/request_token
    W/System.err( 1337): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    W/System.err( 1337): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    W/System.err( 1337): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)
    W/System.err( 1337): Caused by: java.io.FileNotFoundException: http://twitter.com/oauth/request_token
    W/System.err( 1337): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:1162)
    W/System.err( 1337): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18)
    W/System.err( 1337): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228)
    W/System.err( 1337): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    W/System.err( 1337): … 2 more

  22. says

    Hi!!

    Thanks for the awesome twitter app! I only have one question: Why it has to be type “browser”?

    A twitter app for android isn’t a client type?

    Thanks!

    Best Regards,

  23. Ankit Shah says

    Thanks for step-by-step process and sample code…

    But i have question regarding “Application Type” – as we have implemented twitter related stuff in iPhone where it requires “Application Type” as “Client” – now if i change to “Browser” iPhone implementation stop working… Any help or pointer on this will be appreciated.

  24. Kikoso says

    This is definitely not working. Twitter has not only changed the addresses, plus now is necessary to register a domain to access the application. I haven’t been able yet to post a solution, hope to make it soon :-)

  25. pvu says

    I’m getting similar errors like one of the members from above. I’ve been on this for awhile, this will be my first time connecting to the internet from an android app. I’m sure it has to do with my Twitter & code configurations. So, your help is greatly appreciated.

    Here’s the error when run app example:
    ‘twitter (not connected)’
    Here’s the error after pressing post:
    ‘post to twitter failed’

    Let me know if you need more info. Thanks

      • pvu says

        I hope you don’t mind the long log:

        [2011-07-19 19:11:47 - testconnect] ——————————
        [2011-07-19 19:11:47 - testconnect] Android Launch!
        [2011-07-19 19:11:47 - testconnect] adb is running normally.
        [2011-07-19 19:11:47 - testconnect] Performing net.londatiga.android.TestConnect activity launch
        [2011-07-19 19:11:47 - testconnect] Automatic Target Mode: using existing emulator ‘emulator-5554′ running compatible AVD ‘sdk2_1api7′
        [2011-07-19 19:11:47 - testconnect] WARNING: Application does not specify an API level requirement!
        [2011-07-19 19:11:47 - testconnect] Device API version is 7 (Android 2.1-update1)
        [2011-07-19 19:11:47 - testconnect] Uploading testconnect.apk onto device ‘emulator-5554′
        [2011-07-19 19:11:49 - testconnect] Installing testconnect.apk…
        [2011-07-19 19:12:01 - testconnect] Success!
        [2011-07-19 19:12:02 - testconnect] Starting activity net.londatiga.android.TestConnect on device emulator-5554
        [2011-07-19 20:12:24 - testconnect] ——————————
        [2011-07-19 20:12:24 - testconnect] Android Launch!
        [2011-07-19 20:12:24 - testconnect] adb is running normally.
        [2011-07-19 20:12:24 - testconnect] Performing net.londatiga.android.TestConnect activity launch
        [2011-07-19 20:12:24 - testconnect] Automatic Target Mode: using existing emulator ‘emulator-5554′ running compatible AVD ‘sdk2_1api7′
        [2011-07-19 20:12:25 - testconnect] WARNING: Application does not specify an API level requirement!
        [2011-07-19 20:12:25 - testconnect] Device API version is 7 (Android 2.1-update1)
        [2011-07-19 20:12:28 - testconnect] Application already deployed. No need to reinstall.
        [2011-07-19 20:12:28 - testconnect] Starting activity net.londatiga.android.TestConnect on device emulator-5554
        [2011-07-19 20:12:31 - testconnect] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=net.londatiga.android/.TestConnect }
        [2011-07-19 20:12:31 - testconnect] ActivityManager: Warning: Activity not started, its current task has been brought to the front

  26. Muhammad Rashid says

    Hi,
    Thanks for this awesome post. It is very helpful. Would you like to tell, is it possible to post all these three things (some Text + any image from sd card + any url or link ) in a single post.

    Kind regards,
    Muhammad Rashid

  27. Lexs194 says

    it work,.but after click Authorize app,.
    it freezee,. can’t came back to my app? what wrong,.? (sorry my english)
    this logcat :

    07-31 23:06:23.883: DEBUG/TwitterApp(363): Request token url http://twitter.com/oauth/authorize?oauth_token=qtKQr3Pr7irHiQXwkPBLo2PUmxQHnqXSgVa24Gh0IU
    07-31 23:06:24.453: DEBUG/Twitter-WebView(363): Loading URL: http://twitter.com/oauth/authorize?oauth_token=qtKQr3Pr7irHiQXwkPBLo2PUmxQHnqXSgVa24Gh0IU
    07-31 23:06:37.735: DEBUG/dalvikvm(363): GC freed 5910 objects / 397872 bytes in 199ms
    07-31 23:06:42.314: WARN/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44e49388
    07-31 23:06:52.754: WARN/KeyCharacterMap(363): No keyboard for id 0
    07-31 23:06:52.763: WARN/KeyCharacterMap(363): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
    07-31 23:07:08.004: DEBUG/dalvikvm(363): GC freed 6289 objects / 527216 bytes in 197ms
    07-31 23:07:08.143: DEBUG/webviewglue(363): nativeDestroy view: 0x32d490
    07-31 23:07:08.473: ERROR/webcoreglue(363): The real object has been deleted
    07-31 23:07:08.495: ERROR/webcoreglue(363): The real object has been deleted
    07-31 23:07:08.544: ERROR/webcoreglue(363): The real object has been deleted
    07-31 23:07:08.644: DEBUG/Twitter-WebView(363): Loading URL: https://twitter.com/oauth/authorize
    07-31 23:07:11.205: WARN/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44e7c4b0

  28. Kiran Kala says

    Hi Lorenz..!

    I am getting the following exception while running the app in DEVICE, but where as in EMULATOR it’s working properly..

    oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Received authentication challenge is null

    I nedd the solution as early as possible

    Kiran Kala

    • says

      Hi Kiran, i don’t know what exactly cause the problem. Error ‘Received authentication challenge is null’ may raised when
      java.net.HttpURLConnection receives a 401 (Unauthorized) from the server. Do you use different sdk on emulator and device?

  29. Kiran Kala says

    Hi Lorenz..!

    I am eagerly waiting for your response..,and I have one more query
    i.e.,whether TWITTER will work in Android 2.1 or not, because..My application is working for 2.2 but not its not supported it 2.1, when I tried to execute in 2.1 I am getting the above error..

    Kiran Kala

  30. Sujit says

    updateStaus not working using twitter4j-core2.1.6. and throws an exception is there any change that i need to make

  31. Andi says

    Hi guys! I have the same issue as Kiran Kala. 2.2 and above is working and on a 2.1 device or emulator is not. Does somebody have any idea why is this happening?

    Thanks!
    Andi

  32. Shawn says

    Thanks for the guide. I thought I would post my experience.

    1) Didn’t work with latest twitter4j-2.2.4 build. Sorry, I didn’t keep the error output, but the problems seems to be that package paths have changed. I used the 2.1.6 branch bundled in the ExtJars file to resolve the problem.

    2) Instructions for setting application type have changed. There is no more option for setting application type to Browser. Instead you just need to specify a callback URL or you will see this error in the debug output.

    java.io.FileNotFoundException: https://api.twitter.com/oauth/request_token

    I found this message in a TCP packet capture.

    /oauth/request_token Desktop applications only support the oauth_callback value ‘oob’

    Here is some additional information.
    http://groups.google.com/group/twitter-development-talk/browse_thread/thread/0f744fe83fd9ef90?pli=1
    https://dev.twitter.com/discussions/282

    Thanks for the tutorial. Only took an hour for me to add Twitter feature with your help.

  33. veljko says

    hey, im using you app and cant post message to twitter. im getting: “Post to twitter failed”

    in log cat i get only this:

    08-15 13:46:34.570: WARN/KeyCharacterMap(2253): Can’t open keycharmap file
    08-15 13:46:34.570: WARN/KeyCharacterMap(2253): Error loading keycharmap file ‘/system/usr/keychars/AT_Translated_Set_2_keyboard.kcm.bin’. hw.keyboards.65539.devname=’AT Translated Set 2 keyboard’
    08-15 13:46:34.570: WARN/KeyCharacterMap(2253): Using default keymap: /system/usr/keychars/qwerty.kcm.bin

    and this:

    08-15 13:45:32.740: DEBUG/UpdaterService(1347): Updater ran.
    08-15 13:45:33.220: ERROR/UpdaterService(1347): Updater.run exception: winterwell.jtwitter.TwitterException: 401 Unauthorized http://twitter.com/statuses/friends_timeline.json

    any idea?

      • veljko says

        yes i did…i got this working, i had a problem with proxy server access.

        Thx for quick answer.

        Anyway, i need to have option of changing twitter account. How do I do that?

        I’ve add a new button, and on click, im doing this:

        mTwitter.resetAccessToken();
        mTwitter.configureToken();
        mTwitter.authorize();

        after seting up new user name and password in authorize dialog, im getting “Twitter connecection failed”

        in logcat im getting:

        08-18 13:44:34.109: WARN/System.err(1941): java.lang.IllegalStateException: consumer key/secret pair already set.
        08-18 13:44:34.109: WARN/System.err(1941): at twitter4j.TwitterOAuthSupportBaseImpl.setOAuthConsumer(TwitterOAuthSupportBaseImpl.java:234)
        08-18 13:44:34.109: WARN/System.err(1941): at twitter4j.Twitter.setOAuthConsumer(Twitter.java:54)
        08-18 13:44:34.109: WARN/System.err(1941): at com.tweeter.TwitterApp.configureToken(TwitterApp.java:74)
        08-18 13:44:34.109: WARN/System.err(1941): at com.tweeter.TwitterApp$3.run(TwitterApp.java:152)

        How do I solve that?

        Hope for quick response.

          • veljko says

            Hey, yes i did.

            This code runs in moment when im logged on twitter with one account. When i click on “change account” button, i need to log out, and sign in as a different user…You know what i mean?

            in changeAccount onClickListener i do this:

            mTwitter = null;

            mTwitter = new TwitterApp(getBaseContext(),
            twitter_consumer_key, twitter_secret_key);
            mTwitter.resetAccessToken();

            if (mTwitter.hasAccessToken()) {
            postToTwitter = mTwitterBtn.isChecked();
            } else {
            mTwitterBtn.setChecked(false);
            mTwitter.authorize();

            }

            The logcat gives me this:
            08-22 20:50:21.059: ERROR/AndroidRuntime(278): FATAL EXCEPTION: main
            08-22 20:50:21.059: ERROR/AndroidRuntime(278): android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application

            on line when im calling authorize method. for re-loging in.

            Help.

    • says

      same problem here,
      at the fist time when application running, i can do a success login to my acount, and ehen i want to legout and then login again, it become failed to connect to my acount.
      thanks for share before. :)

  34. Prayag says

    Not working for me…dont know what happened..assigned my own consumer key and secret key…still not working.says “initializing” and the dialog for authentication doent appear

  35. Nicolas says

    Hi lorenz, it works like a champ! But im having a problem. After I authorize my app on twitter it returns me a PIN… it says i have to go back to my app and type in the given PIN, but… not sure how to do that…

    Thanks,!

    Nico.

  36. Andrea says

    Thanks a lot for this lorenz!

    The only problem I run into is that using 2.1 API level after I enter my credentials and try to login a blank page appears and nothing is happening.

  37. Prayag says

    While Creating an app in twitter there was no option like browser or client,why?

    And the following is my LOGCAT

    09-03 11:32:51.035: DEBUG/TwitterApp(301): Failed to get request token

    09-03 11:32:51.045: WARN/System.err(301): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Host is unresolved: twitter.com:80

    09-03 11:32:51.085: WARN/System.err(301): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)

    09-03 11:32:51.085: WARN/System.err(301): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)

    09-03 11:32:51.095: WARN/System.err(301): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)

    09-03 11:32:51.105: WARN/System.err(301): Caused by: java.net.UnknownHostException: Host is unresolved: twitter.com:80

    09-03 11:32:51.114: WARN/System.err(301): at java.net.Socket.connect(Socket.java:1038)

    09-03 11:32:51.125: WARN/System.err(301): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:62)

    09-03 11:32:51.135: WARN/System.err(301): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:88)

    09-03 11:32:51.135: WARN/System.err(301): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHTTPConnection(HttpURLConnectionImpl.java:927)

    09-03 11:32:51.155: WARN/System.err(301): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:909)

    09-03 11:32:51.155: WARN/System.err(301): at oauth.signpost.basic.DefaultOAuthProvider.sendRequest(DefaultOAuthProvider.java:48)
    09-03 11:32:51.185: WARN/System.err(301): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:177)

    09-03 11:32:51.185: WARN/System.err(301): … 2 more

    09-03 11:32:51.435: WARN/InputManagerService(58): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@43ef6fc0

    • says

      Hi, Twitter has changed the app settings page, there is no setting for client type anymore. From you logcat, i think the problem was on your network connection.

  38. bharadwaj says

    hi..i downloaded this and when i import this to my application and after typing the status message and when i click on twitter button nothing is happening,still its just showing the same main UI…please help me out….

  39. bharadwaj says

    hi..when i am clicking on the twitter check box button to connect to twitter its showing twitter connection failed,and its displaying these messages on the log cat:

    DEBUG/TwitterApp(291): Failed to get request token.
    oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Received authentication challenge is null.

    WARN/System.err(291): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    09-15 16:20:22.083: WARN/System.err(291): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    09-15 16:20:22.093: WARN/System.err(291): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)
    09-15 16:20:22.093: WARN/System.err(291): Caused by: java.io.IOException: Received authentication challenge is null
    09-15 16:20:22.093: WARN/System.err(291): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.doRequestInternal(HttpURLConnection.java:1596)
    09-15 16:20:22.103: WARN/System.err(291): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.doRequest(HttpURLConnection.java:1551)
    09-15 16:20:22.112: WARN/System.err(291): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getResponseCode(HttpURLConnection.java:1273)
    09-15 16:20:22.112: WARN/System.err(291): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getStatusCode(HttpURLConnectionResponseAdapter.java:22)
    09-15 16:20:22.122: WARN/System.err(291): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:178)
    09-15 16:20:22.122: WARN/System.err(291): … 2 more
    09-15 16:20:22.163: INFO/NotificationService(60): enqueueToast pkg=net.londatiga.android callback=android.app.ITransientNotification$Stub$Proxy@44de4738 duration=1
    09-15 16:20:22.253: WARN/InputManagerService(60): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44e3ab40

    please help me out…

    • says

      Do you use Android 2.1? Try to use api.twitter.com instead of twitter.com on:

      mHttpOauthprovider = new DefaultOAuthProvider(“http://twitter.com/oauth/request_token”,
      “http://twitter.com/oauth/access_token”,
      “http://twitter.com/oauth/authorize”);

  40. says

    i always error authencticate at class TestConnect “Twitter Connection Failed”, but if i authenticate at TestPost i always success, why it happen? as i know they use a same function but the result is different? ?

    • jatin says

      here is my logcat…

      09-28 14:54:20.094: INFO/ActivityManager(62): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0×10000000 cmp=net.londatiga.android/.TestConnect } from pid 659
      09-28 14:54:20.134: DEBUG/AndroidRuntime(659): Shutting down VM
      09-28 14:54:20.153: DEBUG/dalvikvm(659): GC_CONCURRENT freed 102K, 69% free 319K/1024K, external 0K/0K, paused 1ms+1ms
      09-28 14:54:20.174: DEBUG/dalvikvm(659): Debugger has detached; object registry had 1 entries
      09-28 14:54:20.174: INFO/AndroidRuntime(659): NOTE: attach of thread ‘Binder Thread #3′ failed
      09-28 14:54:20.414: DEBUG/dalvikvm(615): GC_EXPLICIT freed 404K, 54% free 2660K/5703K, external 1861K/2137K, paused 598ms
      09-28 14:54:21.194: INFO/ActivityManager(62): Displayed net.londatiga.android/.TestConnect: +1s87ms
      09-28 14:54:25.124: DEBUG/TwitterApp(615): Failed to get request token
      09-28 14:54:25.165: WARN/System.err(615): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://api.twitter.com/oauth/request_token
      09-28 14:54:25.165: WARN/System.err(615): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
      09-28 14:54:25.165: WARN/System.err(615): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
      09-28 14:54:25.173: WARN/System.err(615): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)
      09-28 14:54:25.184: WARN/System.err(615): Caused by: java.io.FileNotFoundException: http://api.twitter.com/oauth/request_token
      09-28 14:54:25.184: WARN/System.err(615): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:519)
      09-28 14:54:25.234: WARN/System.err(615): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18)
      09-28 14:54:25.234: WARN/System.err(615): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228)
      09-28 14:54:25.234: WARN/System.err(615): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
      09-28 14:54:25.234: WARN/System.err(615): … 2 more
      09-28 14:54:25.673: WARN/InputManagerService(62): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@40797598
      09-28 14:54:29.734: DEBUG/dalvikvm(134): GC_EXPLICIT freed 36K, 52% free 2917K/5959K, external 5201K/6458K, paused 49ms

  41. Huseyin says

    Hi, firstly thanks alot.

    I can login but, when I try to post a message; ıt returns “401:Authentication credentials were missing or incorrect.
    {“error”:”Could not authenticate with OAuth.”,”request”:”\/1\/statuses\/update.json”}
    “.

    What Should I do? My account is readable and writeable…

  42. Huseyin says

    hi, firstly thanks alot for codes and article.
    I use your codes, and I can login. When I try to post a message, it returns to me ” 401:Authentication credentials were missing or incorrect.
    {“error”:”Could not authenticate with OAuth.”,”request”:”\/1\/statuses\/update.json”}

    What Should I Do? My account is readable and writable…

  43. Kaushal Sharma says

    Hi Lorenz,

    Can you please suggest some for the same “How to Post Twitter Status from Android” with “Sencha Touch” in place of “Android”?

    -Thanks,
    Kaushal

  44. Aaron says

    Greetings,

    Having an issue w/ TwitterApp.java, line 115:

    authURL = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);

    All that my application is doing, is creating the TwitterApp object, setting the listener, checking for accessToken (authorize if not) and then attempting to post.

    If I use https oauth URLs, I get a runtime error:

    OAuthCommunicationsException
    cause- IOException
    detail message- Communication with the service provider failed: Hostname ‘api.twitter.com’ was not verified

    If I use http oauth URLs, I get a different error:

    OAuthCommunicationsException
    cause- FileNotFoundException
    detail message- Communication with the service provider failed: http://api.twitter.com/oauth/request_token

    I’ve searched and searched and cannot find any solution to this. Any assistance would be appreciated.

    Thanks,
    Aaron

    • Aaron says

      After a little more experimentation, I was able to get by this by entering a valid URL for the Callback URL on dev.twitter.com/apps and placing the exact same URL in my app.

      This only works with http, https still throws the same error.

      Regards,
      Aaron

    • says

      api.twitter.com should work on android 2.1 and above. If you use twitter.com/oauth you may have issue with android 2.1. Did u test in emulator or on real device?

  45. Doularam says

    11-09 11:04:28.052: W/System.err(620): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Received authentication challenge is null
    11-09 11:04:28.082: W/System.err(620): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    11-09 11:04:28.092: W/System.err(620): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    11-09 11:04:28.092: W/System.err(620): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)
    11-09 11:04:28.102: W/System.err(620): Caused by: java.io.IOException: Received authentication challenge is null
    11-09 11:04:28.142: W/System.err(620): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequestInternal(HttpURLConnectionImpl.java:1694)
    11-09 11:04:28.142: W/System.err(620): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequest(HttpURLConnectionImpl.java:1649)
    11-09 11:04:28.162: W/System.err(620): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1374)
    11-09 11:04:28.182: W/System.err(620): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getStatusCode(HttpURLConnectionResponseAdapter.java:22)
    11-09 11:04:28.192: W/System.err(620): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:178)
    11-09 11:04:28.202: W/System.err(620): … 2 more
    11-09 11:04:28.542: W/InputManagerService(58): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44fc5bf0

  46. Doularam says

    11-09 11:04:28.052: W/System.err(620): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Received authentication challenge is null
    11-09 11:04:28.082: W/System.err(620): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    11-09 11:04:28.092: W/System.err(620): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    11-09 11:04:28.092: W/System.err(620): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)
    11-09 11:04:28.102: W/System.err(620): Caused by: java.io.IOException: Received authentication challenge is null
    11-09 11:04:28.142: W/System.err(620): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequestInternal(HttpURLConnectionImpl.java:1694)
    11-09 11:04:28.142: W/System.err(620): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequest(HttpURLConnectionImpl.java:1649)
    11-09 11:04:28.162: W/System.err(620): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1374)
    11-09 11:04:28.182: W/System.err(620): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getStatusCode(HttpURLConnectionResponseAdapter.java:22)
    11-09 11:04:28.192: W/System.err(620): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:178)
    11-09 11:04:28.202: W/System.err(620): … 2 more
    11-09 11:04:28.542: W/InputManagerService(58): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44fc5bf0

    1) internet connection is works properly.

    2)I Tried to use api.twitter.com instead of twitter.com on:

    mHttpOauthprovider = new DefaultOAuthProvider(”http://twitter.com/oauth/request_token”,
    “http://twitter.com/oauth/access_token”,
    “http://twitter.com/oauth/authorize”);

    3) On emulator i can open twitter.com web site , so internet is working

    Please help i need immediatly.

  47. Amanda says

    Hi lorenz,

    Ive tried your application but it is unable to connect to twitter and it prompts “twitter connection fail”.

    Please advice.

    Thank you!

    • says

      Try to use api.twitter.com instead of twitter.com for oauth url.

      In TwitterApp.java, the url should be like this;

      mHttpOauthprovider = new DefaultOAuthProvider(“http://api.twitter.com/oauth/request_token”,
      “http://api.twitter.com/oauth/access_token”,
      “http://api.twitter.com/oauth/authorize”);

  48. says

    Hi lorenz. Thanks for the great work. I do all of this (I’ve downloaded your zip file and altered it slightly for my consumer key and secret key, but I can’t get the web view to return to the app. It just goes to the callback URL. I use the callback url http://redir.domain.com (domain is actually replaced with my client’s domain name). My web host sends .domain.com to http://www.domain.com, so the webview just shows the http://www.domain.com page.

  49. Ahariss says

    hello, i am getting this error when i click connect button,knowing that i set the consumer key and consumer secret key below this is my log file when i pressed connect button:

    11-15 19:51:47.200: D/TwitterApp(401): Failed to get request token
    11-15 19:51:47.240: W/System.err(401): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://api.twitter.com/oauth/request_token
    11-15 19:51:47.240: W/System.err(401): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    11-15 19:51:47.240: W/System.err(401): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    11-15 19:51:47.240: W/System.err(401): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:121)
    11-15 19:51:47.240: W/System.err(401): Caused by: java.io.FileNotFoundException: http://api.twitter.com/oauth/request_token
    11-15 19:51:47.280: W/System.err(401): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:519)
    11-15 19:51:47.280: W/System.err(401): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18)
    11-15 19:51:47.280: W/System.err(401): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228)
    11-15 19:51:47.311: W/System.err(401): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    11-15 19:51:47.311: W/System.err(401): … 2 more
    11-15 19:51:47.461: W/InputManagerService(60): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4066a188
    11-15 19:51:51.850: D/dalvikvm(141): GC_EXPLICIT freed 116K, 50% free 2999K/5895K, external 4787K/5329K, paused 79ms
    11-15 19:51:57.020: D/dalvikvm(241): GC_EXPLICIT freed 7K, 54% free 2543K/5511K, external 1625K/2137K, paused 178ms
    11-15 19:52:05.221: D/dalvikvm(271): GC_EXPLICIT freed 502K, 55% free 2595K/5703K, external 1625K/2137K, paused 97ms
    11-15 19:52:10.330: D/dalvikvm(317): GC_EXPLICIT freed 728K, 53% free 3105K/6471K, external 1625K/2137K, paused 184ms
    11-15 19:52:15.260: D/dalvikvm(365): GC_EXPLICIT freed 325K, 54% free 2538K/5511K, external 1625K/2137K, paused 104ms

    Any Luck for help please :)? this is exactly what i need for my app.

  50. An=kur says

    Hi lorenz

    Great tutorial. I am a noob to android api and eclipse and stuff, I am facing a problem. I downloaded the jar files that you said, added them to my project. I had created a new project by the name flixtermovie. Now to create the classes TestConnection.java, I right click the src folder of my project flixtermovie and click add class and ype in the name, after that I copy pasted your code.
    The problem is, there are lots of errors, most of them being “cannot be resolved to type” for various things like Activity, TwitterApp,CheckBox and so on,. Im guessing my libraries are not called properly, how do i solve this issue and get your code working on my computer? Please help me out, thanks a lot.

    Regards

  51. Ian Morgan says

    Hi lorenz,

    One thing I noticed is once I logged out, next it will not lead me to login page at all. Why it so? Pls reply me.

      • Dave Wagler says

        Hey Lorenz,

        It seems that even with that fix implemented in October for some reason the second log-in is showing a blank WebView. The first time the user logs in, the Redirecting URL receives an oauth verifier as a parameter, where as the second time the Redirecting URL only contains the oauth token.

        Any help is appreciated. Thanks for the great tutorial.

        • Dave Wagler says

          I believe I actually fixed it. The problem seemed that the web view still considered me logged in even if I reset my preferences/token. In the shouldOverrideUrlLoading method in the TwitterDialog class it was always returning true even if my URL did not start with the CallBack URL. With this in mind I changed the line:

          else if (url.startsWith(“authorize”)) {
          return false;
          }

          to

          } else if (url.contains(“authorize”)) {
          return false;
          }

          and it seems to have fixed my problem. I don’t think this will cause other issues but now when the user wants to log out they are technically signed into the browser they just need to sign out of it as well or just re-authorize the application if they wish.

  52. Ian Morgan says

    Hi lorenz,

    One thing I noticed, After Logging out, next time Iam not leding to login page at all. Why It is So? Pls Reply me.

  53. Willy says

    Hi lorenz,

    I’ve got an error while connect to twitter from android emulator
    I used AVD 2.1 and have change

    mHttpOauthprovider = new DefaultOAuthProvider(
    “https://api.twitter.com/oauth/request_token”, “https://api.twitter.com/oauth/access_token”,
    “https://api.twitter.com/oauth/authorize”);

    fill the consumer and secret key but I still got error like this:

    LogCat:

    11-27 15:59:26.888: DEBUG/TwitterApp(461): Failed to get request token
    11-27 15:59:26.918: WARN/System.err(461): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Host is unresolved: api.twitter.com:443
    11-27 15:59:26.927: WARN/System.err(461): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    11-27 15:59:26.988: WARN/System.err(461): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    11-27 15:59:27.017: WARN/System.err(461): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)
    11-27 15:59:27.017: WARN/System.err(461): Caused by: java.net.UnknownHostException: Host is unresolved: api.twitter.com:443
    11-27 15:59:27.048: WARN/System.err(461): at java.net.Socket.connect(Socket.java:1037)
    11-27 15:59:27.077: WARN/System.err(461): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:62)
    11-27 15:59:27.088: WARN/System.err(461): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager$ConnectionPool.getHttpConnection(HttpConnectionManager.java:145)
    11-27 15:59:27.117: WARN/System.err(461): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager.getConnection(HttpConnectionManager.java:67)
    11-27 15:59:27.127: WARN/System.err(461): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getHTTPConnection(HttpURLConnection.java:821)
    11-27 15:59:27.148: WARN/System.err(461): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:807)
    11-27 15:59:27.180: WARN/System.err(461): at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnection$HttpsEngine.connect(HttpsURLConnection.java:395)
    11-27 15:59:27.188: WARN/System.err(461): at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnection.connect(HttpsURLConnection.java:146)
    11-27 15:59:27.207: WARN/System.err(461): at oauth.signpost.basic.DefaultOAuthProvider.sendRequest(DefaultOAuthProvider.java:48)
    11-27 15:59:27.207: WARN/System.err(461): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:177)
    11-27 15:59:27.207: WARN/System.err(461): … 2 more
    11-27 15:59:27.278: INFO/NotificationService(58): enqueueToast pkg=net.londatiga.android callback=android.app.ITransientNotification$Stub$Proxy@43e189d8 duration=1
    11-27 15:59:27.498: WARN/InputManagerService(58): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@43cda4b8

    • Willy says

      Hi Lorenz,
      I have solved the problem, but when I post to twitter, the emulator said that it is failed

      LogCat:
      11-27 16:40:30.208: INFO/NotificationService(63): enqueueToast pkg=net.londatiga.android callback=android.app.ITransientNotification$Stub$Proxy@44c558e8 duration=0
      11-27 16:40:31.789: INFO/global(313): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
      11-27 16:40:31.809: INFO/NotificationService(63): enqueueToast pkg=net.londatiga.android callback=android.app.ITransientNotification$Stub$Proxy@44c3a178 duration=0

  54. yogi says

    hi,

    An getting an error in Log cat has : “unauthorized access 401 error”.

    Can u plz give me the solution for this.

    Thanks & Br,
    Yogi

  55. TheTime says

    To get this working :

    * set the callback url on twitter web settings page to :
    https://dev.twitter.com/app

    * change this :

    mHttpOauthprovider = new DefaultOAuthProvider(”http://twitter.com/oauth/request_token”,
    “http://twitter.com/oauth/access_token”,
    “http://twitter.com/oauth/authorize”);

    to this :

    mHttpOauthprovider = new DefaultOAuthProvider(”http://api.twitter.com/oauth/request_token”,
    “http://api.twitter.com/oauth/access_token”,
    “http://api.twitter.com/oauth/authorize”);

  56. Addy says

    Hi Lorenz,

    Thanks for this twitter app code, I am getting through all the authorisation bits fine but for some reason I cannot post to twitter, log cat gives me the following error.

    01-16 20:21:02.776: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol

    Hope you can help.

    Cheers

    Addy

  57. dinu says

    for the first time i can able to login, when i try to post tweet app show post to twitter failed. pls give me some suggestion

  58. dinu says

    hi lorenz,

    I got fixed one issue related to posting the tweet. The reason for twitter posting failed is due to app registration in dev.twitter.com which is in read only mode. I updated it to read and write mode which cleared the problem.It worked for me if it is not relevant pls ignore.

  59. says

    Post to Twitter failed

    02-06 17:04:57.402: I/System.out(1214): {“error”:”Invalid \/ expired Token”,”request”:”\/1\/statuses\/update.json”}

    I have login successfully but not able to update status

  60. says

    message :Post to Twitter failed

    02-06 17:04:57.402: I/System.out(1214): {“error”:”Invalid \/ expired Token”,”request”:”\/1\/statuses\/update.json”}

    401:Authentication credentials were missing or incorrect.

  61. Rooban Ponraj says

    I am getting this error in TwitterApp constructor.

    04-04 11:40:05.478: E/AndroidRuntime(558): FATAL EXCEPTION: main
    04-04 11:40:05.478: E/AndroidRuntime(558): java.lang.VerifyError: net.londatiga.android.TwitterApp
    04-04 11:40:05.478: E/AndroidRuntime(558): at net.londatiga.android.TestConnect.onCreate(TestConnect.java:54)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.os.Looper.loop(Looper.java:123)
    04-04 11:40:05.478: E/AndroidRuntime(558): at android.app.ActivityThread.main(ActivityThread.java:4627)
    04-04 11:40:05.478: E/AndroidRuntime(558): at java.lang.reflect.Method.invokeNative(Native Method)
    04-04 11:40:05.478: E/AndroidRuntime(558): at java.lang.reflect.Method.invoke(Method.java:521)
    04-04 11:40:05.478: E/AndroidRuntime(558): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    04-04 11:40:05.478: E/AndroidRuntime(558): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    04-04 11:40:05.478: E/AndroidRuntime(558): at dalvik.system.NativeStart.main(Native Method)

  62. Amit Tiwari says

    Hi lorenz.

    I can login in twitter but my comments are not showing in twitter.I am using android2.1 and I have change the twitter.com to api.twitter.com.But still I am facing the problem.Please help me.

    Thanks

  63. Amit Tiwari says

    Hi Lorenz

    I am using your code .I can login into twitter but I can not see my message into my twitter account.I am using android 2.1 and I have changed the url from twitter.com to api.twitter.com but still I am facing the issue.Please help!

    Thanks

  64. Rommy says

    I downloaded the code and tried it exactly with no changes (except twitter consume key and secret key).
    But, after I ran it, it always bring force close.

    Here’s the logcat:

    04-26 17:33:49.416: E/AndroidRuntime(895): FATAL EXCEPTION: main
    04-26 17:33:49.416: E/AndroidRuntime(895): java.lang.VerifyError: net.londatiga.android.TwitterApp
    04-26 17:33:49.416: E/AndroidRuntime(895): at net.londatiga.android.TestConnect.onCreate(TestConnect.java:52)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.os.Looper.loop(Looper.java:123)
    04-26 17:33:49.416: E/AndroidRuntime(895): at android.app.ActivityThread.main(ActivityThread.java:4627)
    04-26 17:33:49.416: E/AndroidRuntime(895): at java.lang.reflect.Method.invokeNative(Native Method)
    04-26 17:33:49.416: E/AndroidRuntime(895): at java.lang.reflect.Method.invoke(Method.java:521)
    04-26 17:33:49.416: E/AndroidRuntime(895): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    04-26 17:33:49.416: E/AndroidRuntime(895): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    04-26 17:33:49.416: E/AndroidRuntime(895): at dalvik.system.NativeStart.main(Native Method)

    Any solution for my problem???

  65. MIP TECH says

    i download the code and try but is show error i change only key and secretkey other is same but is show me error
    i am already added jar file from your folder

    is show me error twitter4j.TwitterFactory class not found

    04-30 17:47:32.825: E/dalvikvm(247): Could not find class ‘twitter4j.TwitterFactory’, referenced from method net.londatiga.android.TwitterApp.
    04-30 17:47:32.835: W/dalvikvm(247): VFY: unable to resolve new-instance 96 (Ltwitter4j/TwitterFactory;) in Lnet/londatiga/android/TwitterApp;
    04-30 17:47:32.835: D/dalvikvm(247): VFY: replacing opcode 0×22 at 0x000c
    04-30 17:47:32.835: D/dalvikvm(247): Making a copy of Lnet/londatiga/android/TwitterApp;. code (184 bytes)
    04-30 17:47:32.835: W/dalvikvm(247): VFY: unable to find class referenced in signature (Ltwitter4j/http/AccessToken;)
    04-30 17:47:32.835: W/dalvikvm(247): VFY: unable to find class referenced in signature (Loauth/signpost/OAuthProvider;)
    04-30 17:47:32.846: W/dalvikvm(247): VFY: unable to find class referenced in signature (Loauth/signpost/commonshttp/CommonsHttpOAuthConsumer;)
    04-30 17:47:32.855: W/dalvikvm(247): VFY: unable to find class referenced in signature (Ltwitter4j/http/AccessToken;)
    04-30 17:47:32.855: W/dalvikvm(247): VFY: unable to find class referenced in signature (Ltwitter4j/Twitter;)
    04-30 17:47:32.855: I/dalvikvm(247): Could not find method twitter4j.Twitter.setOAuthConsumer, referenced from method net.londatiga.android.TwitterApp.configureToken
    04-30 17:47:32.855: W/dalvikvm(247): VFY: unable to resolve virtual method 210: Ltwitter4j/Twitter;.setOAuthConsumer (Ljava/lang/String;Ljava/lang/String;)V
    04-30 17:47:32.865: D/dalvikvm(247): VFY: replacing opcode 0x6e at 0x000a
    04-30 17:47:32.865: D/dalvikvm(247): Making a copy of Lnet/londatiga/android/TwitterApp;.configureToken code (60 bytes)
    04-30 17:47:32.875: I/dalvikvm(247): Could not find method twitter4j.Twitter.updateStatus, referenced from method net.londatiga.android.TwitterApp.updateStatus
    04-30 17:47:32.875: W/dalvikvm(247): VFY: unable to resolve virtual method 211: Ltwitter4j/Twitter;.updateStatus (Ljava/lang/String;)Ltwitter4j/Status;
    04-30 17:47:32.875: D/dalvikvm(247): VFY: replacing opcode 0x6e at 0×0002
    04-30 17:47:32.875: D/dalvikvm(247): Making a copy of Lnet/londatiga/android/TwitterApp;.updateStatus code (44 bytes)
    04-30 17:47:32.875: W/dalvikvm(247): VFY: unable to resolve exception class 95 (Ltwitter4j/TwitterException;)
    04-30 17:47:32.875: W/dalvikvm(247): VFY: unable to find exception handler at addr 0×6
    04-30 17:47:32.875: W/dalvikvm(247): VFY: rejected Lnet/londatiga/android/TwitterApp;.updateStatus (Ljava/lang/String;)V
    04-30 17:47:32.875: W/dalvikvm(247): VFY: rejecting opcode 0x0d at 0×0006
    04-30 17:47:32.875: W/dalvikvm(247): VFY: rejected Lnet/londatiga/android/TwitterApp;.updateStatus (Ljava/lang/String;)V
    04-30 17:47:32.875: W/dalvikvm(247): Verifier rejected class Lnet/londatiga/android/TwitterApp;
    04-30 17:47:32.875: D/AndroidRuntime(247): Shutting down VM
    04-30 17:47:32.875: W/dalvikvm(247): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
    04-30 17:47:32.885: E/AndroidRuntime(247): Uncaught handler: thread main exiting due to uncaught exception
    04-30 17:47:32.885: E/AndroidRuntime(247): java.lang.VerifyError: net.londatiga.android.TwitterApp
    04-30 17:47:32.885: E/AndroidRuntime(247): at net.londatiga.android.TestConnect.onCreate(TestConnect.java:52)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.os.Looper.loop(Looper.java:123)
    04-30 17:47:32.885: E/AndroidRuntime(247): at android.app.ActivityThread.main(ActivityThread.java:4363)
    04-30 17:47:32.885: E/AndroidRuntime(247): at java.lang.reflect.Method.invokeNative(Native Method)
    04-30 17:47:32.885: E/AndroidRuntime(247): at java.lang.reflect.Method.invoke(Method.java:521)
    04-30 17:47:32.885: E/AndroidRuntime(247): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
    04-30 17:47:32.885: E/AndroidRuntime(247): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    04-30 17:47:32.885: E/AndroidRuntime(247): at dalvik.system.NativeStart.main(Native Method)
    04-30 17:47:32.905: I/dalvikvm(247): threadid=7: reacting to signal 3
    04-30 17:47:32.905: E/dalvikvm(247): Unable to open stack trace file ‘/data/anr/traces.txt’: Permission denied
    04-30 17:49:41.555: W/ActivityThread(270): Application net.londatiga.android is waiting for the debugger on port 8100…
    04-30 17:49:41.575: I/System.out(270): Sending WAIT chunk
    04-30 17:49:41.644: I/dalvikvm(270): Debugger is active
    04-30 17:49:41.785: I/System.out(270): Debugger has connected
    04-30 17:49:41.785: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:41.985: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:42.246: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:42.455: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:42.655: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:42.858: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:43.129: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:43.347: I/System.out(270): waiting for debugger to settle…
    04-30 17:49:43.619: I/System.out(270): debugger has settled (1364)
    04-30 17:49:44.035: E/dalvikvm(270): Could not find class ‘twitter4j.TwitterFactory’, referenced from method net.londatiga.android.TwitterApp.
    04-30 17:49:44.035: W/dalvikvm(270): VFY: unable to resolve new-instance 96 (Ltwitter4j/TwitterFactory;) in Lnet/londatiga/android/TwitterApp;
    04-30 17:49:44.035: D/dalvikvm(270): VFY: replacing opcode 0×22 at 0x000c
    04-30 17:49:44.035: D/dalvikvm(270): Making a copy of Lnet/londatiga/android/TwitterApp;. code (184 bytes)
    04-30 17:49:44.045: W/dalvikvm(270): VFY: unable to find class referenced in signature (Ltwitter4j/http/AccessToken;)
    04-30 17:49:44.055: W/dalvikvm(270): VFY: unable to find class referenced in signature (Loauth/signpost/OAuthProvider;)
    04-30 17:49:44.065: W/dalvikvm(270): VFY: unable to find class referenced in signature (Loauth/signpost/commonshttp/CommonsHttpOAuthConsumer;)
    04-30 17:49:44.075: W/dalvikvm(270): VFY: unable to find class referenced in signature (Ltwitter4j/http/AccessToken;)
    04-30 17:49:44.085: W/dalvikvm(270): VFY: unable to find class referenced in signature (Ltwitter4j/Twitter;)
    04-30 17:49:44.095: I/dalvikvm(270): Could not find method twitter4j.Twitter.setOAuthConsumer, referenced from method net.londatiga.android.TwitterApp.configureToken
    04-30 17:49:44.095: W/dalvikvm(270): VFY: unable to resolve virtual method 210: Ltwitter4j/Twitter;.setOAuthConsumer (Ljava/lang/String;Ljava/lang/String;)V
    04-30 17:49:44.095: D/dalvikvm(270): VFY: replacing opcode 0x6e at 0x000a
    04-30 17:49:44.095: D/dalvikvm(270): Making a copy of Lnet/londatiga/android/TwitterApp;.configureToken code (60 bytes)
    04-30 17:49:44.145: I/dalvikvm(270): Could not find method twitter4j.Twitter.updateStatus, referenced from method net.londatiga.android.TwitterApp.updateStatus
    04-30 17:49:44.145: W/dalvikvm(270): VFY: unable to resolve virtual method 211: Ltwitter4j/Twitter;.updateStatus (Ljava/lang/String;)Ltwitter4j/Status;
    04-30 17:49:44.145: D/dalvikvm(270): VFY: replacing opcode 0x6e at 0×0002
    04-30 17:49:44.145: D/dalvikvm(270): Making a copy of Lnet/londatiga/android/TwitterApp;.updateStatus code (44 bytes)
    04-30 17:49:44.155: W/dalvikvm(270): VFY: unable to resolve exception class 95 (Ltwitter4j/TwitterException;)
    04-30 17:49:44.155: W/dalvikvm(270): VFY: unable to find exception handler at addr 0×6
    04-30 17:49:44.155: W/dalvikvm(270): VFY: rejected Lnet/londatiga/android/TwitterApp;.updateStatus (Ljava/lang/String;)V
    04-30 17:49:44.155: W/dalvikvm(270): VFY: rejecting opcode 0x0d at 0×0006
    04-30 17:49:44.155: W/dalvikvm(270): VFY: rejected Lnet/londatiga/android/TwitterApp;.updateStatus (Ljava/lang/String;)V
    04-30 17:49:44.155: W/dalvikvm(270): Verifier rejected class Lnet/londatiga/android/TwitterApp;
    04-30 17:51:07.896: W/jdwp(270): Debugger is telling the VM to exit with code=1
    04-30 17:51:07.896: I/dalvikvm(270): GC lifetime allocation: 2511 bytes

  66. ramesh says

    hi lorenz, i need to implement the twitter posting but not only text but images also can you suggest some post for that also.

  67. ganesh says

    hey lorenz..

    this help me a lot thx for posting.. authentication is working proparly..but when i posting any text..its saying post failed plz help me….

  68. ganesh says

    hey Lorenze

    thax for posting this artical, it help me lot..I am using your code .I can login into twitter but whenver im posting any tweet it saying tweet post is failed plz help..I am using android 2.2 google API

  69. John Nogueira says

    Just in case anyone wanted to know how to clear the user’s credentials from the Twitter webview… (In addition to clearing the access token from the app’s shared preferences, this modification forces the user to re-enter their username and password on the Twitter webview when signing back-on).

    1. In twitterapp.java, replace resetAccessToken function with this:

    public void resetAccessToken(Context context) {
    if (mAccessToken != null) {
    mSession.resetAccessToken();

    //clear webview cookies (in case user saved credentials on Twitter webview)
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();

    mAccessToken = null;
    }
    }

    2. From main activity, call:

    mTwitter.resetAccessToken(this);

    • krishna kanth says

      THANK U VERY MUCH FOR YOUR POST … i AM TRYING TO RELOGIN INTO TWIITTER FROM 6 MONTHS ………… BUT WHOMEVER I ASK THEY JUST SAY ONE SIMPLE THING IN TWITTER THERE IS SINGLE SIGN IN ON SO U CANNOT RELOGIN AGAIN AND ALSO ONCE YOU HAVE LOGGED IN YOU CANNOT LOGOUT. But u proved that they are wrong and thank u very very much for your post… It helped a department in a very big way … thank u very much … :)

  70. Upendra says

    I got Exception here…

    mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

    The Exception is::::

    E/AndroidRuntime(318): java.lang.VerifyError: net.londatiga.android.TwitterApp

  71. ganesh says

    hey lorenze,

    how to post image with tweet using twitter API without using twitpic. if u hav any demo or sample code then post me the link

    thnk you in advance

  72. krishna kanth says

    Hello lorenze, thanks for your post. I am able to connect to twitter and post successfully. But when i deleted the connection and try to connect again it is not working. It is showing a blank white page and also it is not calling the onError method in TwDialogListener. Please tell me where it was going wrong?

  73. fjr619 says

    i wanna ask something. i can connect to twitter. but when i logout and i want to login again, it just stuck in white page. so what must i do for fix that problem?i really need this app for study about twitter connection.thanks

  74. Vijay says

    When i am click on Submit it will display a Toast :: Review Post then after sometime another Toast display “Post To Twitter Failed.”.

    please Solve it…. please…. please….

  75. Can says

    Hi, I need a help about that codes.

    I downloaded your project. It’s working properly. But I wanted to build my own app. I imported the jar files. There is no problem. Then I take your TwitterApp.java file, TwitterDialog.java file and TwitterSession.java files to my package. I’m trying to login to twitter when I click on a button. When I create the instance of TwitterApp I got a problem. It gives me error on this code;

    mTwitter = new TwitterApp(getApplicationContext(), twitter_consumer_key,
    twitter_secret_key);

    and then crashes the application.

    I couldn’t figure it out

  76. asp17 says

    hi,

    I downloaded your project. It gives me error on this code;

    mTwitter = new TwitterApp(getApplicationContext(), twitter_consumer_key,twitter_secret_key);

    and then crashes the application.

    plz help me.

  77. Rubyd says

    I downloaded this code. But it gives me Error …. :’(

    mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);The Exception is::::
    java.lang.VerifyError: net.londatiga.android.TwitterApp

    ———————————–
    Pls solve this,

    • Ramesh Annadurai says

      Hi Rubyd,

      1) Remove the libraries from the standard Java build path :

      Right click on the project name > Properties > Java Build Path > tab Libraries > remove everything except the “Android X.X” (2.3.3 in my case) and the “Android Dependencies”

      2) Copy the jar files into libs folder :

      a. Create “libs” folder in your project directory without double quotes.

      b. Copy all the required jar files and paste in libs folder.

      c. clean the project.

      By doing that, all the libraries in the folder “libs” are found by the Android plugin and are added to the “Android Dependencies” item of the project

      Thanks,
      RAMESH ANNADURAI

        • Talal Qaboos says

          i have same problem that RubyD have.. i have also try the way Ramesh told to make a libs folder and paste all jar packages into it. but error is same on mTwitter on create(Bundle). in TestConnect class.. my logs are
          06-03 19:18:12.774: E/AndroidRuntime(18667): FATAL EXCEPTION: main
          06-03 19:18:12.774: E/AndroidRuntime(18667): java.lang.VerifyError: net.londatiga.android.TwitterApp
          06-03 19:18:12.774: E/AndroidRuntime(18667): at net.londatiga.android.TestConnect.onCreate(TestConnect.java:52)
          06-03 19:18:12.774: E/AndroidRuntime(18667): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1065)

          please help me pleaseeeeeeee :( :’(

  78. joseph says

    Hi,

    I downloaded your application and just modified the twitter_consumer_key and twitter_secret_key and set it to my app key. Im using android 2.3.3. Looks like its not working perfectly.

    The problem is the app unable to connect to twitter.

    This are the logs:

    08-14 18:02:46.613: D/TwitterApp(3830): Failed to get request token
    08-14 18:02:46.613: W/System.err(3830): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://twitter.com/oauth/request_token
    08-14 18:02:46.613: W/System.err(3830): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    08-14 18:02:46.613: W/System.err(3830): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    08-14 18:02:46.613: W/System.err(3830): at net.londatiga.android.TwitterApp$2.run(TwitterApp.java:117)
    08-14 18:02:46.613: W/System.err(3830): Caused by: java.io.FileNotFoundException: http://twitter.com/oauth/request_token
    08-14 18:02:46.613: W/System.err(3830): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
    08-14 18:02:46.613: W/System.err(3830): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18)
    08-14 18:02:46.623: W/System.err(3830): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228)
    08-14 18:02:46.623: W/System.err(3830): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
    08-14 18:02:46.623: W/System.err(3830): … 2 more

    Any sugestion and comments are very much appreciated.
    Thanks in advance.

  79. Yahya says

    I’ve set:

    REQUEST_TOKEN = “https://api.twitter.com/oauth/request_token”;
    ACCESS_TOKEN = “https://api.twitter.com/oauth/access_token”;
    AUTHORIZE = “https://api.twitter.com/oauth/authorize”;

    and now it works… But i have a problem with CALLBACK_URL… I’ve set it to None when i create twitter app and now it’s not returning token to app, just require user to get pin code into app, and stuck there… What should i do? How should the CALLBACK_URL be?

    Thanks in advance…

  80. Boon says

    hi,i get this when i postToTwitter :-

    TwitterException{exceptionCode=[15bb6564-00e4d61f], statusCode=401, retryAfter=0, rateLimitStatus=null, version=2.1.5-SNAPSHOT(build: d372a51b9b419cbd73d416474f4a855f3e889507)}

  81. Murali says

    Hi,

    When i logout to current user and try to login to another user am getting login filed.Am also clearing cookiemanager.am getting following errors.

    08-30 16:20:04.344: W/System.err(1846): java.lang.IllegalStateException: consumer key/secret pair already set.
    08-30 16:20:04.344: W/System.err(1846): at twitter4j.TwitterOAuthSupportBaseImpl.setOAuthConsumer(TwitterOAuthSupportBaseImpl.java:234)
    08-30 16:20:04.344: W/System.err(1846): at twitter4j.Twitter.setOAuthConsumer(Twitter.java:54)
    08-30 16:20:04.353: W/System.err(1846): at net.londatiga.android.TwitterApp.configureToken(TwitterApp.java:78)
    08-30 16:20:04.353: W/System.err(1846): at net.londatiga.android.TwitterApp.access$7(TwitterApp.java:76)
    08-30 16:20:04.353: W/System.err(1846): at net.londatiga.android.TwitterApp$3.run(TwitterApp.java:158)

    help me thanks in advance.

    • Dejan says

      I managed to make it work by re-initializing instance, like this..

      mTwitter.resetAccessToken(this);
      mTwitter = new TwitterApp(this, consumerKey,consumerSecret);
      mTwitter.setListener(mTwLoginDialogListener);
      mTwitter.authorize();

      not sure if this is the right way, but works for me :)

  82. stephen says

    Hi Lorenz,
    I installed your app in my android galaxy y.version 2.3.3.every authorization is done perfectly .when i post a tweet.i m getting a toast that the tweet is posted..but when i check my twitter account..there is no tweet could u help me out

  83. stephen says

    i used the above code with the jar files attached to it…if i m to use the latest upgraded version of the above jar files i m getting error in the source code..so i used the jar files attached below..works fine.but not able to post on wall..got the toast saying the tweet has been posted..

  84. fjr619 says

    i want ask with your code, will access token be expired although user has been login and not logout?and if yes, how to make access token again without login again.

  85. Grayson says

    Hi I’m having a problem connecting to twitter (program starts up in my eclipse emulator and when I click on “Twitter (not connected)” and it tries to connect it comes back with “Twitter Connection Failed”)(the emulator does have an internet connection). I’ve set the twitter_consumer_key and twitter_secret_key in both TestPost.java and TestConnect.java with my own. Other than that I have not changed or added anything else to the code (gotten from github).
    Is there anything else I need to set in the code to connect to Twitter. I would assume there would need to be some sort of username and password, though if it connects to twitter then I would assume Twitter would handle that instead of your code.

  86. iiwak says

    - WARNING: Application does not specify an API level requirement!
    - Device API version is 10 (Android 2.3.7)

    What should I do?
    I use debuging usb connection.
    I debug your facebook connection code before. It work correctly. But I got error on your twitter connection code.
    Help me please.

    • iiwak says

      I try to resolve my problem. I think “TwitterApp.java” not work correctly. I’ll got error when execute “TwitterApp.java”
      Help me, Lorenz.
      :)

  87. rushabh says

    I am getting “Twitter connection failed” error while executing this function:

    mTwitter.authorize();

    in simulator as well as in device i am getting this error. i have all config jar files and also keys.

  88. says

    I had done all the steps which stated above but wen i click connect it shows that twitter connection failed.. can anyone help me out wat mistake i had done…

  89. nita says

    Someone help me please :(
    I’m very new to android, and still learning how to develop an android program.

    I did exactly these steps, but in the end my program is unexpectedly force closed.

    When I checked on the LogCat it show like this:

    11-10 17:15:40.987: E/AndroidRuntime(463): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    11-10 17:15:40.987: E/AndroidRuntime(463): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    11-10 17:15:40.987: E/AndroidRuntime(463): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    11-10 17:15:40.987: E/AndroidRuntime(463): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    11-10 17:15:40.987: E/AndroidRuntime(463): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    11-10 17:15:40.987: E/AndroidRuntime(463): at android.os.Handler.dispatchMessage(Handler.java:99)
    11-10 17:15:40.987: E/AndroidRuntime(463): at android.os.Looper.loop(Looper.java:123)
    11-10 17:15:40.987: E/AndroidRuntime(463): at android.app.ActivityThread.main(ActivityThread.java:3683)
    11-10 17:15:40.987: E/AndroidRuntime(463): at java.lang.reflect.Method.invokeNative(Native Method)
    11-10 17:15:40.987: E/AndroidRuntime(463): at java.lang.reflect.Method.invoke(Method.java:507)
    11-10 17:15:40.987: E/AndroidRuntime(463): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    11-10 17:15:40.987: E/AndroidRuntime(463): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    11-10 17:15:40.987: E/AndroidRuntime(463): at dalvik.system.NativeStart.main(Native Method)

    Does anyone know what is the problem?

    Thanks before~

  90. says

    Wonderful blog! I found it while searching on Yahoo
    News. Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there! Cheers

  91. venkat says

    thank you for your blog.I used your code and starting a am getting force close.This is the error displayed in logcat:java.lang.VerifyError: net.londatiga.android.TwitterApp.Please help me,I dont know why I am getting this error.

  92. Krish says

    hai i tried this code…i replaced my secret key and consumer key for this code..no errors but wen i run this in emulator always its giving twitter connection failed..i could not solve this problem…please solve this…thanks in advance..
    Lorenz…

  93. Krish says

    hey i solved it..i forgot to give secret key and consumer key in TestPost.java…
    But why we need again in in this java file…any way we authenticated in TestConnect.java file..
    Thanks Lorenz..

  94. ynmly says

    thanks for yourr blog….i have tried both facebook and twitter..facebook one running excellent…but i am facing problem in twitter..it give an error of :-

    [2013-04-03 16:51:48 - Dex Loader] Unable to execute dex: Multiple dex files define Ltwitter4j/TwitterBase;
    [2013-04-03 16:51:48 - AndroidTwitter-master] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Ltwitter4j/TwitterBase;
    [2013-04-03 17:35:19 - Dex Loader] Unable to execute dex: Multiple dex files define Ltwitter4j/TwitterBase;
    [2013-04-03 17:35:19 - AndroidTwitter-master] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Ltwitter4j/TwitterBase;

    could you plz plz me
    thanks lorenz..

  95. Krishnaveni says

    Hi Good Evening..i have downloaded twitter app from here:https://github.com/lorensiuswlt/AndroidTwitter
    here i have to run the app which means the twitter login page is opened.
    i have enter correct login detail means its go to post page..here i have wrote Hi Good morning.afterthat click submit button means thr review posted message is displayed on app.Now i have to check my twitter home page means the data is not posted.
    why the message is didn’t post on home
    please give me solution for these

  96. ynmly says

    hey
    i have tried your code..but i am getting only one error in twitterApp.java file in this line
    “mtwitter.setOAuthAccessToken(mAccess)”

    could you plz help me out….i added all jar file

  97. scratchdisk says

    Thanks for the example app. I did have to update the URLs to get things working. Thanks again.

    mHttpOauthprovider = new DefaultOAuthProvider(“https://api.twitter.com/oauth/request_token”,
    “https://api.twitter.com/oauth/access_token”,
    “https://api.twitter.com/oauth/authorize”);

    • Ram says

      Hi,
      i have updated the urls and tokens but i am getting “twitter connection failed” did u resolved the issue ?

  98. Bipin says

    Hi,

    I have added all the library into project and it was working perfectly before 11 June 2013, now its showing the error connection failled, can you please sortout this issue,so that we can use the example code further. i think its happening due to change in api from v1 to v1.1.

    Thanks

    Bipin

    • Awais says

      if u download it from guihb in that libs folder is missing . Download the jar files and include in your project it’ll work fine

  99. Awais says

    Hi,
    Dear admin you have write a very good article , i am using that and working very good. I just want to know the flow , if you can guide me, it would be great help

  100. Mithun says

    Thanks for your tutorial, Its saves my day.
    And can you please tell me how to get user data like User Full name, email address etc.
    Thanks in advance.

  101. raies says

    i downloaded the code but i’m unable to authroize. when i click on authorize button it redirects me back to first screen and toast a login failed how can i login and post a tweet

  102. suny says

    Having problem with callback url
    i have tried many ways but failed
    talking about mobile app

    after authenticating , it goes to url that i have set on dev.twitter.com rather than coming back to app front page.if i set it to blank then there’s also an error

    i want it to return to app front page …what should i do :(
    thnxx

  103. Nabeel Ahmed says

    Hi folk,
    I am using your Tutorial, but when I run this on mobile device this gives error “Twitter (Not Connected)”

    I want to get rid this problem please help me soon. . .

Leave a Reply

Your email address will not be published. Required fields are marked *