How to Send Image to Twitpic from Android

Twitpic is one of the most common used image hosting that allows users to easily post images to Twitter and other social media. Twitpic can be used independently of Twitter, in a way similar to Google Picasa or Flickr. TwitPic usernames and passwords are the same as the ones in Twitter so it doesn’t have to create new account on Twitpic.

As many other social media, Twitpic also provides RESTful API to enable developers to post image to Twitpic. The current version at the time of this writing is version 2 (V2). Using this API, we can build an Android application that features an image upload to Twitpic so we don’t have to create a new infrastructure for image hosting server.

In this tutorial i’ll explain how to send image to Twitpic from an Android application using Twitter4j library. The source code for this tutorial can be downloaded from my github page (see the download link at the bottom of this post).

I. Register Application

To enable an Android application to send image to Twitpic, first you have to register your application to get an API Key. To get an API Key:

  • Go to Twitpic developer page and click the Register link. If you’re not logged in before, you have to sign in to Twitpic using your Twitter account.
    android twitpic register app
  • Register your application.
    android twitpic register app
  • Save the API Key.
    android twitpic apikey

II. Android Integration

In my sample project i use Twitter4j library to send image to Twitpic. You can download the latest version from Twitter4j download page or use the library package  i’ve provided in this tutorial. To enable Android to send image to Twitpic, first you have to connect to Twitter first using a Twitter account. How to connect to Twitter will not be explained here, you can read my previous tutorial on how to post Twitter status from Android. So basically to be enable to send image to Twitpic, first you have to sign in to Twitter, get the access token and use the access token along with Twitter consumer key, secret key and Twitpic API key.

android twitpic eclipse

In my sample project, i create two packages. The first is for Twitter library, which can be found also on my previous Twitter tutorial sample project and the second is the main application page.

Connect to Twitter (ConnectActivity.java)

This activity displays the Twitter login page and  authenticates user to get the access token. More comprehensive explanation can be found on my previous tutorial.

android twitter signin android twitter signin

Send Image to Twitpic (SendImageActivity.java)

In this activity, using an image picker, the image to be sent can be from existing images on sdcard or directly taking a picture from camera. You can read my previous tutorial on how to create image picker on Android to get more deep understanding on how it works. The classes from Twitter4j that are used to send image to Twitpic are:

import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.http.AccessToken;
import twitter4j.http.OAuthAuthorization;
import twitter4j.util.ImageUpload;
 private class ImageSender extends AsyncTask<URL, Integer, Long> {
    	private String url;

    	protected void onPreExecute() {
			mProgressDialog = ProgressDialog.show(SendImageActivity.this, "", "Sending image...", true);

			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
		}

        protected Long doInBackground(URL... urls) {
            long result = 0;

            TwitterSession twitterSession	= new TwitterSession(SendImageActivity.this);
            AccessToken accessToken 		= twitterSession.getAccessToken();

			Configuration conf = new ConfigurationBuilder()
            .setOAuthConsumerKey(twitter_consumer_key)
            .setOAuthConsumerSecret(twitter_secret_key)
            .setOAuthAccessToken(accessToken.getToken())
            .setOAuthAccessTokenSecret(accessToken.getTokenSecret())
            .build();

			OAuthAuthorization auth = new OAuthAuthorization (conf, conf.getOAuthConsumerKey (), conf.getOAuthConsumerSecret (),
	                new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()));

	        ImageUpload upload = ImageUpload.getTwitpicUploader (twitpic_api_key, auth);

	        Log.d(TAG, "Start sending image...");

	        try {
	        	url = upload.upload(new File(mPath));
	        	result = 1;

	        	Log.d(TAG, "Image uploaded, Twitpic url is " + url);
	        } catch (Exception e) {
	        	Log.e(TAG, "Failed to send image");

	        	e.printStackTrace();
	        }

            return result;
        }

        protected void onProgressUpdate(Integer... progress) {
        }

        protected void onPostExecute(Long result) {
        	mProgressDialog.cancel();

        	String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";

        	Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
        }
    }

In this example, i use asynchronous task to send image to Twitpic, you can use more convenience way to send the image such as using background service with queue to manage uploading multiple images. The main code for sending image to Twitpic defined in doInBackground() method.

line 14: create an object of TwitterSession class to get the accsess token that was previously saved when user was successfully authenticated.

line 15: get the access token object.

line 16: create the configuration object with Twitter consumer key, secret key, access token and access token secret as parameters.

line 24: create the authorization object.

line 27: create the Twitpic image uploader object.

line 32: upload the image file to Twitpic, the method uses file path to the image that was selected from image picker.

lin3 35: if success, the upload method will return the Twitpic url to the uploaded image, ex: http://twitpic.com/6hqd44

android twitpic

Download

 

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

  1. krishna kanth says

    Hello Lorenz this post was really really Helpul But i want to know how to upload VIDEO to twitter, i mean local video file. If you have any sample posts plz mail me …

    Thanks in advance,

    • says

      Hi Krishna, i have no experience on uploading video. But i think the best way is to upload it to public video server then link it to twitter.

  2. krishna kanth says

    I am not able to upload large images .. i mean not very large, images around 1MB or above. I don’t know why? Do I have to optimize my code further or it is there any limit for uploading image

  3. Slim says

    Hi sir please i have an error in the application, i just import it and i aded the libreries but it didnt work, this is my LogCat :
    04-01 21:15:28.793: I/Logger(15687): Will use class twitter4j.internal.logging.CommonsLoggingLoggerFactory as logging factory.
    04-01 21:15:28.793: I/HttpClientFactory(15687): Will use twitter4j.internal.http.HttpClientImpl as HttpClient implementation.
    04-01 21:15:39.834: D/TwitterApp(15687): Failed to get request token
    04-01 21:15:39.898: W/System.err(15687): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Received authentication challenge is null
    04-01 21:15:39.898: W/System.err(15687): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
    04-01 21:15:39.898: W/System.err(15687): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
    04-01 21:15:39.898: W/System.err(15687): at net.londatiga.android.twitter.TwitterApp$2.run(TwitterApp.java:117)
    04-01 21:15:39.898: W/System.err(15687): Caused by: java.io.IOException: Received authentication challenge is null
    04-01 21:15:39.898: W/System.err(15687): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:1153)
    04-01 21:15:39.964: W/System.err(15687): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:1095)
    04-01 21:15:39.964: W/System.err(15687): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1048)
    04-01 21:15:39.964: W/System.err(15687): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:726)
    04-01 21:15:39.964: W/System.err(15687): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getStatusCode(HttpURLConnectionResponseAdapter.java:22)
    04-01 21:15:39.964: W/System.err(15687): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:178)
    04-01 21:15:39.964: W/System.err(15687): … 2 more
    04-01 21:15:40.079: E/erreur :(15687): Error getting request token

      • NemoDo says

        I have fixed it, open TwitterApp.java and edit source follow
        mHttpOauthprovider = new DefaultOAuthProvider(“https://twitter.com/oauth/request_token”,
        “https://twitter.com/oauth/access_token”,
        “https://twitter.com/oauth/authorize”);

        But I still can not get token after authorize app.

  4. jay says

    Hi This is veru helpfull code but i got once problem gettin null access token
    I have used below gode . I lreday have token and token secret.
    Configuration conf = new ConfigurationBuilder()
    .setOAuthConsumerKey(Constants.CONSUMER_KEY)
    .setOAuthConsumerSecret(Constants.CONSUMER_SECRET)
    .setOAuthAccessToken(token)
    .setOAuthAccessTokenSecret(secret).build();
    AccessToken a = new AccessToken(conf.getOAuthAccessToken(),coconf.getOAuthAccessTokenSecret());

    on above two line getting null access token.

  5. Bhavik says

    Hi,i am able to upload on twitpic but it doesnt synchronize automatically with twitter. can you help me to sync twitpic with twitter?

    Thanks,
    Bhavik

  6. Android Twitter issue while click on icaon says

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

  7. Android Twitter loging issue while Click on Login Icon says

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

  8. says

    I used your code and it worked.But in the first time when we click to twitter logo to display twitter login dialog is ok but the second and more,it only display dialog but when no content in it..I don’t know why? Do you give that problem?

  9. srinivas says

    Hi,
    I am using your code, when I try to upload picture, it gives me fallowing exception.

    TwitterException(exceptionCode=[f69e96cd-132d4ff3]).

  10. Jay says

    Hey I am using twitpic and its great application and thanks a lot to help us.
    I need on more help from you i got a url of twitpic uploaded image how i post it on twitter without any new authentication please Help Me.

  11. Jay says

    i got error when i add code of TestPost.java into AndroidTwitpic example

    401:Authentication credentials were missing or incorrect.

    {“error”:”Read-only application cannot POST”,”request”:”\/1\/statuses\/update.json”}

    TwitterException{exceptionCode=[15bb6564-00e4d61f], statusCode=401, retryAfter=0, rateLimitStatus=null, version=2.1.6}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:308)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:72)
    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:103)
    at twitter4j.Twitter.updateStatus(Twitter.java:500)
    at net.londatiga.android.twitter.TwitterApp.updateStatus(TwitterApp.java:101)
    at net.londatiga.android.twitpic.ConnectActivity$7.run(ConnectActivity.java:284

  12. says

    Hii, thanx for the great tutorial. But, when I tired to use it in my application I got the error:
    Received authentication challenge is nullTwitterException{exceptionCode=[f69e96cd-132d5002 883a7a68-527cabed], statusCode=-1, retryAfter=0, rateLimitStatus=null, version=2.1.6}

    Please HELP!!!!!!!

  13. netta says

    hey i import AndroidTwitpic-master but it Exclamation and

    import oauth.signpost.OAuthProvider;
    import oauth.signpost.basic.DefaultOAuthProvider;
    import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

    import twitter4j.Twitter;
    import twitter4j.TwitterException;
    import twitter4j.TwitterFactory;
    import twitter4j.http.AccessToken;
    import twitter4j.User;

    it error

    tell me please

  14. sumit says

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

  15. Heba says

    hi
    pls can u help me in this error i use ur project on github but this error appeare in twitterApp class :
    mTwitter.setOAuthAccessToken(mAccessToken);

    the error is :
    The method setOAuthAccessToken(AccessToken) in the type OAuthSupport is not applicable for the arguments (AccessToken)

    i just copy paste ur code what is the problem

  16. Ravi says

    Hi,
    It is really good tutorial,Could u please tell how to get
    ImageUpload upload = ImageUpload.getTwitpicUploader (twitpic_api_key, auth); class getting compile time error.

  17. febbry R says

    Hi ,

    I have successfully post the image to twitter. But Twitpic is always return the same url of image although it’s different image. have you got that problem?

Leave a Reply

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