Example usage for twitter4j StatusUpdate StatusUpdate

List of usage examples for twitter4j StatusUpdate StatusUpdate

Introduction

In this page you can find the example usage for twitter4j StatusUpdate StatusUpdate.

Prototype

public StatusUpdate(String status) 

Source Link

Usage

From source file:com.ibuildapp.romanblack.FanWallPlugin.SharingActivity.java

License:Open Source License

/**
 * Post button and home button handler./*from w w  w.ja v  a2s. c o  m*/
 */
public void onClick(View arg0) {
    final String edittext = mainEditText.getText().toString();

    if (arg0 == homeImageView) {
        finish();
    } else if (arg0 == postImageView) {
        if (!Utils.networkAvailable(SharingActivity.this)) {
            handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
            return;
        }

        if (sharingType.equalsIgnoreCase("facebook")) {
            handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                        String photo_name = "IMG_IBUILDAPP_" + timeStamp + ".jpg";

                        String message_text = edittext;

                        // *************************************************************************************************
                        // preparing sharing message
                        String downloadThe = getString(R.string.directoryplugin_email_download_this);
                        String androidIphoneApp = getString(R.string.directoryplugin_email_android_iphone_app);
                        String postedVia = getString(R.string.directoryplugin_email_posted_via);
                        String foundThis = getString(R.string.directoryplugin_email_found_this);

                        // prepare content
                        String downloadAppUrl = String.format("http://%s/projects.php?action=info&projectid=%s",
                                Statics.BASE_DOMEN, com.ibuildapp.romanblack.FanWallPlugin.data.Statics.APP_ID);

                        String adPart = ""; /*String.format(downloadThe + " %s " + androidIphoneApp + ": %s\n%s",
                                            com.ibuildapp.romanblack.FanWallPlugin.data.Statics.appName,
                                            downloadAppUrl,
                                            postedVia + " http://ibuildapp.com");*/

                        // content part
                        String contentPath = ""; /* String.format(foundThis + " %s: %s \n%s",
                                                 com.ibuildapp.romanblack.FanWallPlugin.data.Statics.appName,
                                                 image_url,
                                                 com.ibuildapp.romanblack.FanWallPlugin.data.Statics.hasAd ? adPart : "");*/

                        message_text += "\n" + contentPath;

                        boolean res = FacebookAuthorizationActivity.sharing(Authorization
                                .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken(),
                                message_text, image_url);
                        if (res)
                            handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_SUCCESS);
                        else
                            handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    } catch (Exception e) {
                        Log.e("", "");
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    }
                }
            }).start();

        } else if (sharingType.equalsIgnoreCase("twitter")) {
            handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        twitter = reInitTwitter();
                        String message_text = edittext;
                        if (com.ibuildapp.romanblack.FanWallPlugin.data.Statics.hasAd == true) {
                            message_text += getString(R.string.directoryplugin_email_posted_via)
                                    + " http://ibuildapp.com.";
                        }

                        if (message_text.length() > 140) {
                            if (TextUtils.isEmpty(image_url))
                                message_text = message_text.substring(0, 110);
                            else
                                message_text = message_text.substring(0, 140 - image_url.length());
                        }

                        StatusUpdate su = new StatusUpdate(message_text);
                        if (!TextUtils.isEmpty(image_url)) {
                            InputStream input = new URL(image_url).openStream();
                            su.setMedia(image_url, input);
                        }
                        twitter.updateStatus(su);
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_SUCCESS);
                    } catch (Exception e) {
                        Log.d("", "");
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    }
                }
            }).start();
        }
    }
}

From source file:com.illusionaryone.TwitterAPI.java

License:Open Source License

public String updateStatus(String statusString, String filename) {
    if (accessToken == null) {
        return "false";
    }/*from ww w .  j a  v a  2 s.  c o m*/

    try {
        StatusUpdate statusUpdate = new StatusUpdate(statusString.replaceAll("@", "").replaceAll("#", ""));
        statusUpdate.setMedia(new File(filename));
        Status status = twitter.updateStatus(statusUpdate);
        com.gmt2001.Console.debug.println("Success");
        return "true";
    } catch (TwitterException ex) {
        com.gmt2001.Console.err.println("Failed: " + ex.getMessage());
        return "false";
    }
}

From source file:com.javielinux.api.loaders.UploadStatusLoader.java

License:Apache License

private boolean updateText(String text, long tweet_id, boolean useGeo) {
    StatusUpdate statusUpdate = new StatusUpdate(text);
    if (useGeo) {
        Location loc = LocationUtils.getLastLocation(getContext());
        GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
        statusUpdate.setLocation(gl);//from w ww  .j  a v a2  s .c o  m
    }
    if (tweet_id > 0)
        statusUpdate.inReplyToStatusId(tweet_id);
    try {
        twitter.updateStatus(statusUpdate);
    } catch (TwitterException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.javielinux.api.loaders.UploadTwitlongerLoader.java

License:Apache License

@Override
public BaseResponse loadInBackground() {

    //TODO: Comprobar el valor devuelto con el valor esperado (error - ready) y el parmetro user_geolocation
    try {/* w  w  w.ja  v a 2 s. c om*/
        Log.d(Utils.TAG, "Enviando a twitlonger: " + tweet_text);

        String textTwitLonger = "";

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.twitlonger.com/api_post");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("application", "tweettopics"));
            nameValuePairs.add(new BasicNameValuePair("api_key", "f7y8lgz31srR46sr"));
            nameValuePairs.add(new BasicNameValuePair("username", twitter.getScreenName()));
            nameValuePairs.add(new BasicNameValuePair("message", tweet_text));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse httpResponse = httpclient.execute(httppost);

            String xml = EntityUtils.toString(httpResponse.getEntity());

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser x = factory.newPullParser();

            x.setInput(new StringReader(xml));

            String error = "";

            int eventType = x.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {
                    if (x.getName().equals("error")) {
                        error = x.nextText();
                    }
                    if (x.getName().equals("content")) {
                        textTwitLonger = x.nextText();
                        Log.d(Utils.TAG, "Enviando a twitter: " + textTwitLonger);
                    }
                }
                eventType = x.next();
            }

            if (!error.equals("")) {
                Log.d(Utils.TAG, "Error: " + error);
                ErrorResponse response = new ErrorResponse();
                response.setError(error);
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorResponse response = new ErrorResponse();
            response.setError(e, e.getMessage());
            return response;
        }

        UploadTwitlongerResponse response = new UploadTwitlongerResponse();

        if (!textTwitLonger.equals("")) {
            StatusUpdate statusUpdate = new StatusUpdate(textTwitLonger);
            if (use_geolocation) {
                Location loc = LocationUtils.getLastLocation(getContext());
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                statusUpdate.setLocation(gl);
            }
            if (tweet_id > 0)
                statusUpdate.inReplyToStatusId(tweet_id);
            twitter.updateStatus(statusUpdate);

            response.setReady(true);
        } else {
            response.setReady(false);
        }

        return response;
    } catch (Exception e) {
        e.printStackTrace();
        ErrorResponse response = new ErrorResponse();
        response.setError(e, e.getMessage());
        return response;
    }
}

From source file:com.javielinux.task.UploadStatusAsyncTask.java

License:Apache License

private boolean updateText(String text, long tweet_id, boolean useGeo) {
    StatusUpdate su = new StatusUpdate(text);
    if (useGeo) {
        Location loc = LocationUtils.getLastLocation(mContext);
        GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
        su.setLocation(gl);/*from  ww  w  . j a va  2s.com*/
    }
    if (tweet_id > 0)
        su.inReplyToStatusId(tweet_id);
    try {
        twitter.updateStatus(su);
    } catch (TwitterException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.javielinux.task.UploadTwitlongerAsyncTask.java

License:Apache License

@Override
protected Boolean doInBackground(String... args) {
    try {//from   ww w.  ja va 2 s . c  o  m
        String text = args[0];
        Log.d(Utils.TAG, "Enviando a twitlonger: " + text);
        long tweet_id = Long.parseLong(args[1]);
        boolean useGeo = args[2].equals("1") ? true : false;

        String textTwitLonger = "";

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.twitlonger.com/api_post");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("application", "tweettopics"));
            nameValuePairs.add(new BasicNameValuePair("api_key", "f7y8lgz31srR46sr"));
            nameValuePairs.add(new BasicNameValuePair("username", twitter.getScreenName()));

            //byte[] utf8Bytes = text.getBytes("UTF8");
            //String textutf8 = new String(utf8Bytes, "UTF8");
            nameValuePairs.add(new BasicNameValuePair("message", text));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse httpResponse = httpclient.execute(httppost);

            String xml = EntityUtils.toString(httpResponse.getEntity());
            try {

                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(true);
                XmlPullParser x = factory.newPullParser();

                x.setInput(new StringReader(xml));

                String error = "";

                int eventType = x.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {
                        if (x.getName().equals("error")) {
                            error = x.nextText();
                        }
                        if (x.getName().equals("content")) {
                            textTwitLonger = x.nextText();
                            Log.d(Utils.TAG, "Enviando a twitter: " + textTwitLonger);
                        }
                    }
                    eventType = x.next();
                }

                if (!error.equals("")) {
                    Log.d(Utils.TAG, "Error: " + error);
                    return true;
                }

            } catch (Exception e) {
                e.printStackTrace();
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }

        if (!textTwitLonger.equals("")) {
            StatusUpdate su = new StatusUpdate(textTwitLonger);
            if (useGeo) {
                Location loc = LocationUtils.getLastLocation(mContext);
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                su.setLocation(gl);
            }
            if (tweet_id > 0)
                su.inReplyToStatusId(tweet_id);
            twitter.updateStatus(su);
        } else {
            return true;
        }

        //} catch (TwitterException e) {
        //   e.printStackTrace();
        //   return true;
    } catch (Exception e) {
        e.printStackTrace();
        return true;
    }
    return false;
}

From source file:com.klinker.android.twitter.services.TweetWearableService.java

License:Apache License

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    final WearableUtils wearableUtils = new WearableUtils();

    final BitmapLruCache cache = App.getInstance(this).getBitmapCache();

    if (markReadHandler == null) {
        markReadHandler = new Handler();
    }//from  w  w  w. j  a  v a2  s  .c o  m

    final String message = new String(messageEvent.getData());
    Log.d(TAG, "got message: " + message);

    final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess()) {
        Log.e(TAG, "Failed to connect to GoogleApiClient.");
        return;
    }

    if (message.equals(KeyProperties.GET_DATA_MESSAGE)) {
        AppSettings settings = AppSettings.getInstance(this);

        Cursor tweets = HomeDataSource.getInstance(this).getWearCursor(settings.currentAccount);
        PutDataMapRequest dataMap = PutDataMapRequest.create(KeyProperties.PATH);
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> screennames = new ArrayList<String>();
        ArrayList<String> bodies = new ArrayList<String>();
        ArrayList<String> ids = new ArrayList<String>();

        if (tweets != null && tweets.moveToLast()) {
            do {
                String name = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_NAME));
                String screenname = tweets
                        .getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_SCREEN_NAME));
                String pic = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_PRO_PIC));
                String body = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_TEXT));
                long id = tweets.getLong(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_TWEET_ID));

                String retweeter;
                try {
                    retweeter = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_RETWEETER));
                } catch (Exception e) {
                    retweeter = "";
                }

                screennames.add(screenname);
                names.add(name);
                if (TextUtils.isEmpty(retweeter)) {
                    body = pic + KeyProperties.DIVIDER + body + KeyProperties.DIVIDER;
                } else {
                    body = pic + KeyProperties.DIVIDER + body + "<br><br>" + getString(R.string.retweeter)
                            + retweeter + KeyProperties.DIVIDER;
                }
                bodies.add(Html.fromHtml(body.replace("<p>", KeyProperties.LINE_BREAK)).toString());
                ids.add(id + "");
            } while (tweets.moveToPrevious()
                    && tweets.getCount() - tweets.getPosition() < MAX_ARTICLES_TO_SYNC);
            tweets.close();
        }

        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_USER_NAME, names);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_USER_SCREENNAME, screennames);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_TWEET, bodies);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_ID, ids);

        // light background with orange accent or theme color accent
        dataMap.getDataMap().putInt(KeyProperties.KEY_PRIMARY_COLOR, Color.parseColor("#dddddd"));
        if (settings.addonTheme) {
            dataMap.getDataMap().putInt(KeyProperties.KEY_ACCENT_COLOR, settings.accentInt);
        } else {
            dataMap.getDataMap().putInt(KeyProperties.KEY_ACCENT_COLOR,
                    getResources().getColor(R.color.orange_primary_color));
        }
        dataMap.getDataMap().putLong(KeyProperties.KEY_DATE, System.currentTimeMillis());

        for (String node : wearableUtils.getNodes(googleApiClient)) {
            byte[] bytes = dataMap.asPutDataRequest().getData();
            Wearable.MessageApi.sendMessage(googleApiClient, node, KeyProperties.PATH, bytes);
            Log.v(TAG, "sent " + bytes.length + " bytes of data to node " + node);
        }
    } else if (message.startsWith(KeyProperties.MARK_READ_MESSAGE)) {
        markReadHandler.removeCallbacksAndMessages(null);
        markReadHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String[] messageContent = message.split(KeyProperties.DIVIDER);

                final long id = Long.parseLong(messageContent[1]);

                final AppSettings settings = AppSettings.getInstance(TweetWearableService.this);

                try {
                    HomeDataSource.getInstance(TweetWearableService.this).markPosition(settings.currentAccount,
                            id);
                } catch (Throwable t) {
                    t.printStackTrace();
                }

                sendBroadcast(new Intent("com.klinker.android.twitter.CLEAR_PULL_UNREAD"));

                final SharedPreferences sharedPrefs = getSharedPreferences(
                        "com.klinker.android.twitter_world_preferences", 0);

                // mark tweetmarker if they use it
                if (AppSettings.getInstance(TweetWearableService.this).tweetmarker) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            TweetMarkerHelper helper = new TweetMarkerHelper(settings.currentAccount,
                                    sharedPrefs.getString("twitter_screen_name_" + settings.currentAccount, ""),
                                    Utils.getTwitter(TweetWearableService.this, settings), sharedPrefs);

                            helper.sendCurrentId("timeline", id);

                            startService(new Intent(TweetWearableService.this, HandleScrollService.class));
                        }
                    }).start();
                } else {
                    startService(new Intent(TweetWearableService.this, HandleScrollService.class));
                }
            }
        }, 5000);

    } else if (message.startsWith(KeyProperties.REQUEST_FAVORITE)) {
        final long tweetId = Long.parseLong(message.split(KeyProperties.DIVIDER)[1]);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this,
                            AppSettings.getInstance(TweetWearableService.this)).createFavorite(tweetId);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_COMPOSE)) {
        final String status = message.split(KeyProperties.DIVIDER)[1];

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this,
                            AppSettings.getInstance(TweetWearableService.this)).updateStatus(status);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_RETWEET)) {
        final long tweetId = Long.parseLong(message.split(KeyProperties.DIVIDER)[1]);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this,
                            AppSettings.getInstance(TweetWearableService.this)).retweetStatus(tweetId);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_REPLY)) {
        final String tweet = message.split(KeyProperties.DIVIDER)[1];
        final long replyToId = Long.parseLong(message.split(KeyProperties.DIVIDER)[2]);

        final StatusUpdate status = new StatusUpdate(tweet);
        status.setInReplyToStatusId(replyToId);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this,
                            AppSettings.getInstance(TweetWearableService.this)).updateStatus(status);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_IMAGE)) {
        final String url = message.split(KeyProperties.DIVIDER)[1];
        Bitmap image = null;

        try {
            cache.get(url).getBitmap();
        } catch (Exception e) {

        }

        if (image != null) {
            image = adjustImage(image);

            sendImage(image, url, wearableUtils, googleApiClient);
        } else {
            // download it
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                        InputStream is = new BufferedInputStream(conn.getInputStream());

                        Bitmap image = decodeSampledBitmapFromResourceMemOpt(is, 500, 500);

                        try {
                            is.close();
                        } catch (Exception e) {

                        }
                        try {
                            conn.disconnect();
                        } catch (Exception e) {

                        }

                        cache.put(url, image);
                        image = adjustImage(image);

                        sendImage(image, url, wearableUtils, googleApiClient);
                    } catch (Exception e) {

                    }
                }
            }).start();
        }
    } else {
        Log.e(TAG, "message not recognized");
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitPicHelper.java

License:Apache License

/**
 * posts the status onto Twitlonger, it then posts the shortened status (with link) to the user's twitter and updates the status on twitlonger
 * to include the posted status's id.//w  ww .j a  v a 2s .  c o m
 *
 * @return id of the status that was posted to twitter
 */
public long createPost() {
    TwitPicStatus status = uploadToTwitPic();
    Log.v("talon_twitpic", "past upload");
    long statusId;
    try {
        Status postedStatus;
        StatusUpdate update = new StatusUpdate(status.getText());

        if (replyToStatusId != 0) {
            update.setInReplyToStatusId(replyToStatusId);
        }
        if (location != null) {
            update.setLocation(location);
        }

        postedStatus = twitter.updateStatus(update);

        statusId = postedStatus.getId();
    } catch (Exception e) {
        e.printStackTrace();
        statusId = 0;
    }

    // if zero, then it failed
    return statusId;
}

From source file:com.krossovochkin.kwitter.tasks.SendReplyAsyncTask.java

License:Apache License

private boolean sendReply(final Twitter twitter, long tweetId, final String tweet) {
    try {/* ww  w  .  j  a v  a 2 s. com*/
        twitter.updateStatus(new StatusUpdate(tweet).inReplyToStatusId(tweetId));
        return true;
    } catch (TwitterException te) {
        Log.e(TAG, "Failed send tweet: " + te.getMessage());
        return false;
    }
}

From source file:com.learnncode.demotwitterimagepost.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final Activity callingActivity,
        final String imageUrl, final String message, final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);/*  w ww  . j  a  va 2  s  . c  om*/
        return;
    }

    final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken(context));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    final Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    final File file = new File(imageUrl);

    new Thread(new Runnable() {

        private double x;

        @Override
        public void run() {
            boolean success = true;
            try {
                x = Math.random();
                if (file.exists()) {
                    final StatusUpdate status = new StatusUpdate(message);
                    status.setMedia(file);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (final Exception e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}