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