Out of 100 application 70 to 80 apps have sharing option either it could be an Android , Iphone or any other platform user can see the sharing Icon which having all social media like FaceBook, Google Plus (G+),Twitter, Mail,etc.
So now a day’s social media is a one of the major part of the application as well as user.
Well here I will share you one of them and that is Twitter Integration in android. So let’s start with coding.
In this post you will learn from starting if you had never implement Twitter in android. You will learn how to share your text message as well as picture also.
In first stage we will learn what should be minimum requirement to integrate Twitter.
Updates :
Dear All i know that my last code was not working and that is due to Twitter4J lib and i have received so many comments to fix it so finally i have build same code with few changes as below.
1. Replace latest jar :
For latest .jar file you can download from http://twitter4j.org/en/ , once you extract the folder you have to replace twitter4j-core-4.0.2.jar & twitter4j-media-support-4.0.2.jar inside the /lib.
2. Fix the Bug;
In previous code i was updating ui (Toast Message) from background thread so that will cause the issue and crashing the application. Now i have update with runOnUiThread so that will not throw the exception.
3. Emulator Testing:
Add SD card size if you are testing in emulator otherwise that will throw Permission error.
And you can get latest code from my Git Page. https://github.com/khetiyachintan/Android-Twitter-Example
Follow the below steps:
Change your Two Keys & Run Sample
Twitte to Twitter
How to convert String Image URL to File or Image ?
// this function will make your image to file
Now up to here i have describe how to config Twitter and how to share image and text in Twitter.Download full code and learn Twitter other files also. How they manage the User
I haven't write a code for Login session so now that is your task how maintain login session and how to Log out.
Hope you like it my post and you will learn grate things form this post.
So now a day’s social media is a one of the major part of the application as well as user.
Well here I will share you one of them and that is Twitter Integration in android. So let’s start with coding.
In this post you will learn from starting if you had never implement Twitter in android. You will learn how to share your text message as well as picture also.
In first stage we will learn what should be minimum requirement to integrate Twitter.
Updates :
Dear All i know that my last code was not working and that is due to Twitter4J lib and i have received so many comments to fix it so finally i have build same code with few changes as below.
1. Replace latest jar :
For latest .jar file you can download from http://twitter4j.org/en/ , once you extract the folder you have to replace twitter4j-core-4.0.2.jar & twitter4j-media-support-4.0.2.jar inside the /lib.
2. Fix the Bug;
In previous code i was updating ui (Toast Message) from background thread so that will cause the issue and crashing the application. Now i have update with runOnUiThread so that will not throw the exception.
3. Emulator Testing:
Add SD card size if you are testing in emulator otherwise that will throw Permission error.
And you can get latest code from my Git Page. https://github.com/khetiyachintan/Android-Twitter-Example
Follow the below steps:
- Open the https://dev.twitter.com/
- My Application > Create New Application
- Fill up some basic >>[ App Name, Description, Web Site, Call back URL ] Everything is mandatory so don’t blank anything you can read more details on same page.
- Click on Checkbox to agree terms and condition
- Write captcha and submit you will be get message to done successfully along with that you will be redirect to your KEY Screen and here is your data which will be use to implement in android.
- You will get Consumer Key & Consumer Secrete Key
- Now select the setting
- > check on Read,Write and Access direct Message
- > also check “Allow this application to be use to sign in with twitter”
Change your Two Keys & Run Sample
public final String consumer_key = "Replace your KEY";
public final String secret_key = "Replace your KEY";
Twitte to Twitter
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | public void onClickTwitt() { if (isNetworkAvailable()) { Twitt_Sharing twitt = new Twitt_Sharing(MainActivity. this , consumer_key, secret_key); // here we have web url image so we have to make it as file to // upload String_to_File(string_img_url); // Now share both message & image to sharing activity twitt.shareToTwitter(string_msg, casted_image); } else { showToast( "No Network Connection Available !!!" ); } } |
public void onClickTwitt() { if (isNetworkAvailable()) { Twitt_Sharing twitt = new Twitt_Sharing(MainActivity.this, consumer_key, secret_key); string_img_url = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtDM4Ix5-AR33BeIaLoSzUkcrcce_sYEfzksCjltOq1INOPJxrRndfQweCI6giHoIvY27g4pvOBdutiRMdOB0LMIQL-HsOEYrPThZXYO_rRVndWUbi_rjhbNDyuf5UnRjJyPii0d2DObQ/s1600/id-do-anything-logo.jpg"; string_msg = "http://idroidhub.blogspot.in/"; // here we have web url image so we have to make it as file to // upload String_to_File(string_img_url); // Now share both message & image to sharing activity twitt.shareToTwitter(string_msg, casted_image); } else { showToast("No Network Connection Available !!!"); } }
How to convert String Image URL to File or Image ?
// this function will make your image to file
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public File String_to_File(String img_url) { try { File rootSdDirectory = Environment.getExternalStorageDirectory(); casted_image = new File(rootSdDirectory, "attachment.jpg" ); if (casted_image.exists()) { casted_image.delete(); } casted_image.createNewFile(); FileOutputStream fos = new FileOutputStream(casted_image); URL url = new URL(img_url); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setRequestMethod( "GET" ); connection.setDoOutput( true ); connection.connect(); InputStream in = connection.getInputStream(); byte [] buffer = new byte [ 1024 ]; int size = 0 ; while ((size = in .read(buffer)) > 0 ) { fos.write(buffer, 0 , size); } fos.close(); return casted_image; } catch (Exception e) { System.out.print(e); // e.printStackTrace(); } return casted_image; } |
public File String_to_File(String img_url) { try { File rootSdDirectory = Environment.getExternalStorageDirectory(); casted_image = new File(rootSdDirectory, "attachment.jpg"); if (casted_image.exists()) { casted_image.delete(); } casted_image.createNewFile(); FileOutputStream fos = new FileOutputStream(casted_image); URL url = new URL(img_url); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); InputStream in = connection.getInputStream(); byte[] buffer = new byte[1024]; int size = 0; while ((size = in .read(buffer)) > 0) { fos.write(buffer, 0, size); } fos.close(); return casted_image; } catch (Exception e) { System.out.print(e); // e.printStackTrace(); } return casted_image; }
Now up to here i have describe how to config Twitter and how to share image and text in Twitter.Download full code and learn Twitter other files also. How they manage the User
REQUEST
and return RESPONSE
according to same.I haven't write a code for Login session so now that is your task how maintain login session and how to Log out.
Hope you like it my post and you will learn grate things form this post.
Nice Information Thank you......for sharing usefull information...
ReplyDeleteIt's good example but it's not posting for new version 4.2 devices in android.Please Update the code for new version 4.2. as soon as possible.
ReplyDeleteHello Chintan I think so u have posted nice sample but using ur code and ur sample consumer key i m getting error as (Posting failed!!!) so can u plz elaborate the following????
ReplyDeletei just want to send only message so how to update ur code plz tell me
ReplyDeleteIn which device are your testing ? and which error you are getting ? Can you share your logcate
ReplyDeleteI am testing on Samsung Galaxy s4.
ReplyDeleteI am getting error as.
"Pic Upload errorError creating status."
Can you please check, why it is not send tweets in 4.2.
i am posting failed
ReplyDeleteThanks Dude, Really Nice Example.
ReplyDeleteTwitt_Sharing twitt = new Twitt_Sharing(MainActivity.this,
ReplyDeleteconsumer_key, secret_key);
--what is the "Twitt_Sharing" .
Not Posting data. "Posting Failed" appeares. Logcat below:
ReplyDelete01-07 06:49:54.564: W/System.err(1255): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-07 06:49:54.564: W/System.err(1255): at android.os.Handler.(Handler.java:197)
01-07 06:49:54.594: W/System.err(1255): at android.os.Handler.(Handler.java:111)
01-07 06:49:54.604: W/System.err(1255): at android.widget.Toast$TN.(Toast.java:324)
01-07 06:49:54.604: W/System.err(1255): at android.widget.Toast.(Toast.java:91)
01-07 06:49:54.604: W/System.err(1255): at android.widget.Toast.makeText(Toast.java:238)
01-07 06:49:54.604: W/System.err(1255): at com.twittershare.Twitter_code.Twitt_Sharing.Share_Pic_Text_Titter(Twitt_Sharing.java:134)
01-07 06:49:54.614: W/System.err(1255): at com.twittershare.Twitter_code.Twitt_Sharing$PostTwittTask.doInBackground(Twitt_Sharing.java:91)
01-07 06:49:54.614: W/System.err(1255): at com.twittershare.Twitter_code.Twitt_Sharing$PostTwittTask.doInBackground(Twitt_Sharing.java:1)
01-07 06:49:54.614: W/System.err(1255): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-07 06:49:54.614: W/System.err(1255): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-07 06:49:54.655: W/System.err(1255): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-07 06:49:54.655: W/System.err(1255): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-07 06:49:54.655: W/System.err(1255): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-07 06:49:54.734: W/System.err(1255): at java.lang.Thread.run(Thread.java:856)
problem uploading image:
ReplyDelete01-07 07:26:06.974: D/TAG(1650): Pic Upload errornull
please help...
Twitt_Sharing where i find
ReplyDeleteim getting error "Login fail"
ReplyDeleteWhen I run example that the app show Toast "login fail" although I put id and password right
ReplyDeleteI am stuck with callback. It will not redirect to myapplication after authorization. will you please explain what to write in place of callback. its urgent.
ReplyDeleteWIth ur callback i am getting a toast message login fail. I don't understand what is the problem. will you please help
ReplyDeleteHere i want to tweet from android app without login .
ReplyDeletei have
public static final String CONSUMER_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String CONSUMER_SECRET ="XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String OATH_TOKEN="4XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String OATH_TOKEN_SECRET="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
is it possible ,if possible could you suggest me.
No its not possible ,How user will authenticate to twit with out login. i don't think so that is possible.
ReplyDeleteYeah even i have face that issue while i was trying to run that demo and that is issue of Twitter 4j Lib i have update some code in my older project i will update soon.
ReplyDeleteHi Chintan, Please update your code with latest working demo, pls pls
ReplyDeleteI have many problem with this sample code. After all, I am really thank you for your source code, and I have advise for all people use this source, you should find latest libs to run it.
ReplyDeleteMate am I wrong or you are subject of a network on main thread exception?
ReplyDeleteI had same issue "Login Failed", I just replace twitter4j latest jars instead of old.
ReplyDeleteYou can find these jars on http://twitter4j.org/en/index.html
Its work for me.
I am sure this paragraph has touched all the internet people, its really really
ReplyDeletegood piece of writing on building up new blog.
Regards
Hi Chintan
ReplyDeletewhen i am shearing a image it showing login failed.when i am giving correct twitter user name and password it is not working me.could help the where i change the code
When I run example that the app show Toast “login fail” although I put id and password right
ReplyDeleteHi!
ReplyDelete"Yeah even i have face that issue while i was trying to run that demo and that is issue of Twitter 4j Lib i have update some code in my older project i will update soon"
You solve problems related to Twitter 4j lib?
Thanks you :).
Sorry i didnt get time to look into code and update. have you try with latest jar ?
ReplyDeleteI had same issue “Login Failed”, I just replace twitter4j latest jars instead of old.
ReplyDeleteYou can find these jars on http://twitter4j.org/en/index.html
Its work for me.
I had same issue “Login Failed”, I just replace twitter4j latest jars instead of old.
ReplyDeleteYou can find these jars on http://twitter4j.org/en/index.html
Its work for me.
Please Explore the package you will get idea.
ReplyDeleteI had same issue “Login Failed”, I just replace twitter4j latest jars instead of old.
ReplyDeleteYou can find these jars on http://twitter4j.org/en/index.html
Its work for me.
Yes, thanks you. I will try. :D
ReplyDeleteHI chintan thanks for the cdoe . I want to open the sharing window before posting so that user can change the text how can i do this please reply
ReplyDeleteAditya, For that you can use Sharing Intent. This code is only for background sharing.
ReplyDeleteHey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example
ReplyDeleteHey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example
ReplyDeleteHey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example
ReplyDeleteHey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example
ReplyDeleteThanks a lot, you saved my life :D
ReplyDeleteSuper code, works like charm, If possible plz add image uploading from url and video sharing too.
ReplyDeleteIt would help many... Thanx for ur code :)
[…] http://chintankhetiya.wordpress.com/2013/07/18/sharing-text-image-in-twitter-android-example/ […]
ReplyDeleteHow to add your own image selected from gallery or taaken from camera instead of your URL image.?
ReplyDeleteHii Chetan.. Thanks for the code..I am not able to share a picture on the twitter.I am getting the exception message "Failed to update on Twitter".
ReplyDeletedid u filled the callback url in twitter api settings..? if the callback field is blank it wont work. add some url altho it dont want to be a correct/actual url.
ReplyDeleteHi,
ReplyDeleteThanks for this project. But i have an issue. I am trying to sign in with my twitter account but then it does not redirect back to the application activity.please reply as soon as possible.Thanks in Advance
When i try to log in with Twitter, it still in the Twitter webView without doing anything, but when i go back and i try to log in the second time, it work directly without asking username and password ( The log in Twitter in two steps ).
ReplyDeleteI did have any exception to debug the problem, this is why i ask you to help me to solve this problem.
I would be very grateful if you can give me some indications.
thank, works like magic :D
ReplyDeleteHello sir , can we post multiple images in single tweet using above code .
ReplyDelete[…] Interesting link, because I need to send both text and an image to be posted on Twitter. […]
ReplyDeletehow will this work?and which device?
ReplyDeleteYes but can't as array.
ReplyDeleteI am a newbie..I would like to login to app via twitter for multiuser.Any help will be appreciated.Thanks in Advance
ReplyDeleteCannot find symbol OAuthProvider showing me this error
ReplyDeleteupdated new twitter4j-core-4.0.4 and twitter4j-media-support-4.0.4, but still facing "Login Failed" issue
ReplyDelete