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

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 WebviewDialog 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.

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.

– 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.

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

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”

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.

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?

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

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?

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.

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 !!

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.

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?

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.

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.

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.

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.

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”.

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.

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 🙂

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’

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?

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..

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.

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. 🙂

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…

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….

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? ?

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”}
“.

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”}
”

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.

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.

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.

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.

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.

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!

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).

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 … 🙂

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?

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

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;

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)

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?

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

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..

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.

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.

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…

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

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.

Hi I am developing an app and I used “https://github.com/lorensiuswlt/NewAndroidTwitter” twitter library for sharing in twitter.It was working perfectly but now it’s not working on Android 4.3(samsung s3),Android 4.1(Sony xperia sl) however it’s working on 4.4 devices(nexus 7 and sony xperia zl).I just debugged the code and it seem’s the issue is caused at the webview.If I am putting a break point on the shouldoverloadingurl method run the step by step it seem’s to work .Guess there is slight timing issue.Do you know anything about it.