1
votes

Twitter recently released an update allowing users to attach up to four images to a tweet. I was wondering how to implement this in an Android application.

I've found a post that was made BEFORE Twitter released the update called "Posting multiple photos in a single tweet" (I'm not showing the link because I'm only allowed to show two links with less than 10 reputation).

Now, here is the Twitter API documentation describing how to attach multiple images to a tweet, the only problem is that I have no idea how to implement this in Android:

https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media

So I was thinking of two possible solutions - either modify one of these methods from the Twitter4j library( https://github.com/yusuke/twitter4j/tree/master/twitter4j-media-support/src/main/java/twitter4j/media) to allow for multiple image attachments OR directly implement the Twitter API documentation.

Any ideas how to do this?

Input is greatly appreciated!

1

1 Answers

0
votes

I have shared the multiple images on Twitter in android using twitter4j library,it is working fine to share multiple and single image on twitter

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

public class SharingActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String PREF_NAME = "sample_twitter_pref";
    private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    private static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";
    private static final String PREF_USER_NAME = "twitter_user_name";
    private static final int WEBVIEW_REQUEST_CODE = 223;

    private static Twitter twitter;
    private static RequestToken requestToken;
    private static SharedPreferences mSharedPreferences;
    private String consumerKey = null;
    private String consumerSecret = null;
    private String callbackUrl = null;
    private String oAuthVerifier = null;
    ImageView loginLayout,shareLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTwitterConfigs();
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        setContentView(R.layout.activity_main);

        findViewById(R.id.twitBtnId).setOnClickListener(this);
        findViewById(R.id.btn_share).setOnClickListener(this);

        mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
        boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
        if (isLoggedIn) {
            loginLayout.setVisibility(View.VISIBLE);
            shareLayout.setVisibility(View.GONE);
        } else {
            loginLayout.setVisibility(View.VISIBLE);
            shareLayout.setVisibility(View.GONE);
        }
    }

    private void saveTwitterInfo(AccessToken accessToken) {
        long userID = accessToken.getUserId();
        User user;
        try {
            user = twitter.showUser(userID);
            String username = user.getName();
            SharedPreferences.Editor e = mSharedPreferences.edit();
            e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
            e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
            e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
            e.putString(PREF_USER_NAME, username);
            e.commit();
        } catch (TwitterException e1) {
            e1.printStackTrace();
        }
    }

    private void initTwitterConfigs() {
        consumerKey = getString(R.string.twitter_consumer_key);
        consumerSecret = getString(R.string.twitter_consumer_secret);
        callbackUrl = getString(R.string.twitter_callback);
        oAuthVerifier = getString(R.string.twitter_oauth_verifier);
    }

    private void loginToTwitter() {

        boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

        if (!isLoggedIn) {

            final ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(consumerKey);
            builder.setOAuthConsumerSecret(consumerSecret);

            final Configuration configuration = builder.build();
            final TwitterFactory factory = new TwitterFactory(configuration);
            twitter = factory.getInstance();

            try {
                requestToken = twitter.getOAuthRequestToken(callbackUrl);
                final Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
                startActivityForResult(intent, WEBVIEW_REQUEST_CODE);

            } catch (TwitterException e) {
                e.printStackTrace();
            }
        } else {

            loginLayout.setVisibility(View.GONE);
            shareLayout.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int responseCode, Intent data) {
        super.onActivityResult(requestCode, responseCode, data);

        if (responseCode == Activity.RESULT_OK) {
            String verifier = data.getExtras().getString(oAuthVerifier);
            try {
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
                saveTwitterInfo(accessToken);
                loginLayout.setVisibility(View.GONE);
                shareLayout.setVisibility(View.VISIBLE);

            } catch (Exception e) {
                Log.e("Twitter Login Failed", e.getMessage());
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.twitBtnId:
                loginToTwitter();
                break;
            case R.id.btn_share:
                new ShareImage().execute();
                break;
        }
    }

    public class ShareImage extends AsyncTask<Void,Void,String>{

        @Override
        protected void onPreExecute() {
            //show progress here
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... voids) {
            return uploadMultipleImages();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //hide progress here    
            Toast.makeText(SharingActivity.this,""+result,Toast.LENGTH_LONG).show();
        }
    }

    public String uploadMultipleImages() {

        try {

            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(consumerKey);
            builder.setOAuthConsumerSecret(consumerSecret);

            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
            AccessToken accessToken = new AccessToken(access_token, access_token_secret);

            try {

                Bitmap bmp[] = {BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1),
                        BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view2),
                        BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view3),
                        BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view4),
                        BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view5)};

                String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
                File folder = new File(dir);
                if (!folder.exists())
                    folder.mkdirs();

                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

                long[] mediaIds = new long[4];
                for (int i=0; i<4; i++) {
                    File tempFile = new File(dir,"image_file"+(i));
                    FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
                    boolean isCompres = bmp[i].compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
                    if (isCompres) {
                        UploadedMedia media = twitter.uploadMedia(tempFile);
                        mediaIds[i] = media.getMediaId();

                        tempFile.deleteOnExit();
                    }
                }

                StatusUpdate update = new StatusUpdate("test_name0");
                update.setMediaIds(mediaIds);
                Status status = twitter.updateStatus(update);
                return "Successfully uploaded";

            } catch (TwitterException te) {
                te.printStackTrace();
                System.out.println("Failed to update status: " + te.getMessage());
            }

        } catch (Exception e){
            e.printStackTrace();
        }
        return "not uloaded";
    }


    public String uploadSingleImage() {

        try {

            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(consumerKey);
            builder.setOAuthConsumerSecret(consumerSecret);

            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
            AccessToken accessToken = new AccessToken(access_token, access_token_secret);

            try {

                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1);

                String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
                File folder = new File(dir);
                if (!folder.exists())
                    folder.mkdirs();

                File tempFile = new File(dir,"image_file"+(i));
                FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
                boolean isCompres = bmp.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);

                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

                StatusUpdate update = new StatusUpdate("test_name0");
                update.setMedia(tempFile);
                Status status = twitter.updateStatus(update);
                return "Successfully uploaded";

            } catch (TwitterException te) {
                te.printStackTrace();
                System.out.println("Failed to update status: " + te.getMessage());
            }

        } catch (Exception e){
            e.printStackTrace();
        }
        return "not uloaded";
    }
}


public class WebViewActivity extends Activity {

    private WebView webView;
    public static String EXTRA_URL = "extra_url";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_webview);
        final String url = this.getIntent().getStringExtra(EXTRA_URL);
        if (null == url) {
            finish();
        }

        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new MyWebViewClient());
        webView.loadUrl(url);
    }


    class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Uri uri = Uri.parse(url);
            String verifier = uri.getQueryParameter(getString(R.string.twitter_oauth_verifier));
            Intent resultIntent = new Intent();
            resultIntent.putExtra(getString(R.string.twitter_oauth_verifier), verifier);
            setResult(RESULT_OK, resultIntent);
            finish();
            return true;
        }
    }

}

for running above code please download the below library and put it in your app libs folder and add it as dependency in gradle file

(1)twitter4j-core-4.0.4.jar (2)twitter4j-media-support-4.0.4.jar (3)twitter4j-stream-4.0.4.jar (4)signpost-commonshttp4-1.2.1.1.jar (5)signpost-core-1.2.1.1.jar (6)signpost-jetty6-1.2.1.1.jar

It is working fine, hope it will help for you also