Thursday 18 July 2013

Sharing Text & Image In Twitter - Android Example

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:

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

Create New Application - 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);
        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 !!!");
    }
}
 
 

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.
Twitter Sharing Twitter Login Dialog



GitHub-download

55 comments:

  1. Nice Information Thank you......for sharing usefull information...

    ReplyDelete
  2. It'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.

    ReplyDelete
  3. Hello 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????

    ReplyDelete
  4. i just want to send only message so how to update ur code plz tell me

    ReplyDelete
  5. In which device are your testing ? and which error you are getting ? Can you share your logcate

    ReplyDelete
  6. I am testing on Samsung Galaxy s4.
    I am getting error as.
    "Pic Upload errorError creating status."
    Can you please check, why it is not send tweets in 4.2.

    ReplyDelete
  7. i am posting failed

    ReplyDelete
  8. Thanks Dude, Really Nice Example.

    ReplyDelete
  9. Twitt_Sharing twitt = new Twitt_Sharing(MainActivity.this,
    consumer_key, secret_key);
    --what is the "Twitt_Sharing" .

    ReplyDelete
  10. Not Posting data. "Posting Failed" appeares. Logcat below:

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

    ReplyDelete
  11. problem uploading image:

    01-07 07:26:06.974: D/TAG(1650): Pic Upload errornull

    please help...

    ReplyDelete
  12. im getting error "Login fail"

    ReplyDelete
  13. When I run example that the app show Toast "login fail" although I put id and password right

    ReplyDelete
  14. I 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.

    ReplyDelete
  15. WIth ur callback i am getting a toast message login fail. I don't understand what is the problem. will you please help

    ReplyDelete
  16. Here i want to tweet from android app without login .
    i 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.

    ReplyDelete
  17. No its not possible ,How user will authenticate to twit with out login. i don't think so that is possible.

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

    ReplyDelete
  19. Hi Chintan, Please update your code with latest working demo, pls pls

    ReplyDelete
  20. I 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.

    ReplyDelete
  21. Mate am I wrong or you are subject of a network on main thread exception?

    ReplyDelete
  22. I had same issue "Login Failed", I just replace twitter4j latest jars instead of old.
    You can find these jars on http://twitter4j.org/en/index.html
    Its work for me.

    ReplyDelete
  23. I am sure this paragraph has touched all the internet people, its really really
    good piece of writing on building up new blog.



    Regards

    ReplyDelete
  24. Hi Chintan
    when 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

    ReplyDelete
  25. When I run example that the app show Toast “login fail” although I put id and password right

    ReplyDelete
  26. Phan Văn Tuấn3 June 2014 at 20:05

    Hi!
    "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 :).

    ReplyDelete
  27. Sorry i didnt get time to look into code and update. have you try with latest jar ?

    ReplyDelete
  28. I had same issue “Login Failed”, I just replace twitter4j latest jars instead of old.
    You can find these jars on http://twitter4j.org/en/index.html
    Its work for me.

    ReplyDelete
  29. I had same issue “Login Failed”, I just replace twitter4j latest jars instead of old.
    You can find these jars on http://twitter4j.org/en/index.html
    Its work for me.

    ReplyDelete
  30. Please Explore the package you will get idea.

    ReplyDelete
  31. I had same issue “Login Failed”, I just replace twitter4j latest jars instead of old.
    You can find these jars on http://twitter4j.org/en/index.html
    Its work for me.

    ReplyDelete
  32. Phan Văn Tuấn4 June 2014 at 19:05

    Yes, thanks you. I will try. :D

    ReplyDelete
  33. HI 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

    ReplyDelete
  34. Aditya, For that you can use Sharing Intent. This code is only for background sharing.

    ReplyDelete
  35. Hey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example

    ReplyDelete
  36. Hey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example

    ReplyDelete
  37. Hey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example

    ReplyDelete
  38. Hey , Thanks for feedback Check update.https://github.com/khetiyachintan/Android-Twitter-Example

    ReplyDelete
  39. Thanks a lot, you saved my life :D

    ReplyDelete
  40. Super code, works like charm, If possible plz add image uploading from url and video sharing too.
    It would help many... Thanx for ur code :)

    ReplyDelete
  41. […] http://chintankhetiya.wordpress.com/2013/07/18/sharing-text-image-in-twitter-android-example/ […]

    ReplyDelete
  42. How to add your own image selected from gallery or taaken from camera instead of your URL image.?

    ReplyDelete
  43. Hii 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".

    ReplyDelete
  44. did 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.

    ReplyDelete
  45. Hi,

    Thanks 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

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

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

    ReplyDelete
  47. thank, works like magic :D

    ReplyDelete
  48. Hello sir , can we post multiple images in single tweet using above code .

    ReplyDelete
  49. […] Interesting link, because I need to send both text and an image to be posted on Twitter. […]

    ReplyDelete
  50. how will this work?and which device?

    ReplyDelete
  51. I am a newbie..I would like to login to app via twitter for multiuser.Any help will be appreciated.Thanks in Advance

    ReplyDelete
  52. Cannot find symbol OAuthProvider showing me this error

    ReplyDelete
  53. updated new twitter4j-core-4.0.4 and twitter4j-media-support-4.0.4, but still facing "Login Failed" issue

    ReplyDelete