Example usage for twitter4j Twitter getMentionsTimeline

List of usage examples for twitter4j Twitter getMentionsTimeline

Introduction

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

Prototype

ResponseList<Status> getMentionsTimeline(Paging paging) throws TwitterException;

Source Link

Document

Returns the 20 most recent mentions (tweets containing a users's @screen_name) for the authenticating user.<br> The timeline returned is the equivalent of the one seen when you view your mentions on twitter.com.<br> This method can only return up to 800 tweets.<br> See <a href="https://dev.twitter.com/docs/working-with-timelines">Working with Timelines</a> for instructions on traversing timelines.

Usage

From source file:com.daiv.android.twitter.services.CatchupPull.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    if (CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning
            || !MainActivity.canSwitch) {
        return;/*w  w w.ja  v a 2 s  .  c  o m*/
    }
    CatchupPull.isRunning = true;

    Log.v("Test_pull", "catchup pull started");

    sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    final Context context = getApplicationContext();

    int unreadNow = sharedPrefs.getInt("pull_unread", 0);

    // stop it just in case
    context.sendBroadcast(new Intent("com.daiv.android.twitter.STOP_PUSH_SERVICE"));

    AppSettings settings = AppSettings.getInstance(context);

    if (settings.liveStreaming) {
        Log.v("Test_pull", "into the try for catchup service");
        Twitter twitter = Utils.getTwitter(context, settings);

        HomeDataSource dataSource = HomeDataSource.getInstance(context);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        List<Status> statuses = new ArrayList<Status>();

        boolean foundStatus = false;

        Paging paging = new Paging(1, 200);

        long[] lastId;
        long id;

        try {
            lastId = dataSource.getLastIds(currentAccount);
            id = lastId[0];
        } catch (Exception e) {
            context.startService(new Intent(context, TestPullNotificationService.class));
            CatchupPull.isRunning = false;
            return;
        }

        try {
            paging.setSinceId(id);
        } catch (Exception e) {
            paging.setSinceId(1l);
        }

        for (int i = 0; i < settings.maxTweetsRefresh; i++) {
            try {
                if (!foundStatus) {
                    paging.setPage(i + 1);
                    List<Status> list = twitter.getHomeTimeline(paging);

                    statuses.addAll(list);

                    if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) {
                        Log.v("Test_inserting", "found status");
                        foundStatus = true;
                    } else {
                        Log.v("Test_inserting", "haven't found status");
                        foundStatus = false;
                    }

                }
            } catch (Exception e) {
                // the page doesn't exist
                foundStatus = true;
                e.printStackTrace();
            } catch (OutOfMemoryError o) {
                // don't know why...
                o.printStackTrace();
            }
        }

        Log.v("Test_pull", "got statuses, new = " + statuses.size());

        // hash set to remove duplicates I guess
        HashSet hs = new HashSet();
        hs.addAll(statuses);
        statuses.clear();
        statuses.addAll(hs);

        Log.v("Test_inserting", "tweets after hashset: " + statuses.size());

        lastId = dataSource.getLastIds(currentAccount);

        int inserted = dataSource.insertTweets(statuses, currentAccount, lastId);

        if (inserted > 0 && statuses.size() > 0) {
            sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId())
                    .commit();
            unreadNow += statuses.size();
        }

        if (settings.preCacheImages) {
            // delay it 15 seconds so that we can finish checking mentions first
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startService(new Intent(context, PreCacheService.class));
                }
            }, 15000);
        }

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
    }

    try {
        Twitter twitter = Utils.getTwitter(context, settings);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        User user = twitter.verifyCredentials();
        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

        long[] lastId = dataSource.getLastIds(currentAccount);
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId[0] > 0) {
            paging.sinceId(lastId[0]);
        }

        List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging);

        int numNew = dataSource.insertTweets(statuses, currentAccount);

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();

        if (settings.notifications && settings.mentionsNot && numNew > 0) {
            NotificationUtils.refreshNotification(context);
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }

    sharedPrefs.edit().putInt("pull_unread", unreadNow).commit();
    context.startService(new Intent(context, TestPullNotificationService.class));

    context.sendBroadcast(new Intent("com.daiv.android.Test.UPDATE_WIDGET"));
    getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null);

    Log.v("Test_pull", "finished with the catchup service");

    CatchupPull.isRunning = false;
}

From source file:com.daiv.android.twitter.services.MentionsRefreshService.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Context context = getApplicationContext();
    AppSettings settings = AppSettings.getInstance(context);

    // if they have mobile data on and don't want to sync over mobile data
    if (Utils.getConnectionStatus(context) && !settings.syncMobile) {
        return;/*from   www .j  av a  2s  .co  m*/
    }

    try {
        Twitter twitter = Utils.getTwitter(context, settings);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

        long[] lastId = dataSource.getLastIds(currentAccount);
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId[0] > 0) {
            paging.sinceId(lastId[0]);
        }

        List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging);

        int inserted = MentionsDataSource.getInstance(context).insertTweets(statuses, currentAccount);

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();

        if (settings.notifications && settings.mentionsNot && inserted > 0) {
            if (intent.getBooleanExtra("from_launcher", false)) {
                NotificationUtils.refreshNotification(context, true);
            } else {
                NotificationUtils.refreshNotification(context);
            }
        }

        if (settings.syncSecondMentions) {
            startService(new Intent(context, SecondMentionsRefreshService.class));
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }
}

From source file:com.daiv.android.twitter.services.SecondMentionsRefreshService.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Context context = getApplicationContext();
    AppSettings settings = AppSettings.getInstance(context);

    // if they have mobile data on and don't want to sync over mobile data
    if (Utils.getConnectionStatus(context) && !settings.syncMobile) {
        return;//  w  ww.  j a v  a  2s.  c o  m
    }

    boolean update = false;
    int numberNew = 0;

    try {
        Twitter twitter = Utils.getSecondTwitter(context);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        if (currentAccount == 1) {
            currentAccount = 2;
        } else {
            currentAccount = 1;
        }

        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

        long lastId = dataSource.getLastIds(currentAccount)[0];
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId > 0) {
            paging.sinceId(lastId);
        }

        List<Status> statuses = twitter.getMentionsTimeline(paging);

        numberNew = MentionsDataSource.getInstance(context).insertTweets(statuses, currentAccount);

        if (numberNew > 0) {
            sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();

            if (settings.notifications && settings.mentionsNot) {
                NotificationUtils.notifySecondMentions(context, currentAccount);
            }

            sendBroadcast(new Intent("com.daiv.android.twitter.REFRESH_SECOND_MENTIONS"));
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }
}

From source file:com.javielinux.database.EntityTweetUser.java

License:Apache License

public InfoSaveTweets saveTweets(Context context, Twitter twitter) {

    InfoSaveTweets out = new InfoSaveTweets();

    try {//from ww w.  j  a va2  s.  c o m
        String where = "type_id = " + tweet_type + " AND user_tt_id=" + getId();

        int nResult = DataFramework.getInstance().getEntityListCount("tweets_user", where);
        if (nResult > 0)
            mLastIdNotification = DataFramework.getInstance().getTopEntity("tweets_user", where, "date desc")
                    .getLong("tweet_id");

        boolean breakTimeline = false;

        PreferenceManager.setDefaultValues(context, R.xml.preferences, false);
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);

        int maxDownloadTweet = Integer.parseInt(pref.getString("prf_n_max_download", "60"));
        if (maxDownloadTweet <= 0)
            maxDownloadTweet = 60;

        ResponseList<twitter4j.Status> statii = null;
        ResponseList<twitter4j.DirectMessage> directs = null;

        if (mLastIdNotification > 0) {
            if (tweet_type == TweetTopicsUtils.TWEET_TYPE_TIMELINE) {

                Paging p = new Paging(1, maxDownloadTweet);
                p.setSinceId(mLastIdNotification);

                try {
                    statii = twitter.getHomeTimeline(p);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                }

                if (statii != null && statii.size() >= maxDownloadTweet - 10) {
                    p = new Paging(1, 10);
                    p.setSinceId(mLastIdNotification);
                    p.setMaxId(statii.get(statii.size() - 1).getId());
                    if (twitter.getHomeTimeline().size() > 0) {
                        breakTimeline = true;
                    }
                }

            } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_MENTIONS) {
                Paging p = new Paging();
                p.setCount(100);
                p.setSinceId(mLastIdNotification);
                statii = twitter.getMentionsTimeline(p);
            } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_DIRECTMESSAGES) {
                Paging p = new Paging();
                p.setCount(100);
                p.setSinceId(mLastIdNotification);
                directs = twitter.getDirectMessages(p);
            } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_SENT_DIRECTMESSAGES) {
                Paging p = new Paging();
                p.setCount(100);
                p.setSinceId(mLastIdNotification);
                directs = twitter.getSentDirectMessages(p);
            }
        } else {
            try {
                Log.d(Utils.TAG, "Primera carga de " + getTypeText());
                if (tweet_type == TweetTopicsUtils.TWEET_TYPE_TIMELINE) {
                    statii = twitter.getHomeTimeline(new Paging(1, 40));
                } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_MENTIONS) {
                    statii = twitter.getMentionsTimeline(new Paging(1, 40));
                } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_DIRECTMESSAGES) {
                    directs = twitter.getDirectMessages();
                } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_SENT_DIRECTMESSAGES) {
                    directs = twitter.getSentDirectMessages();
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }

        // guardar statii

        if (statii != null) {

            if (statii.size() > 0) {
                out.setNewMessages(statii.size());
                out.setNewerId(statii.get(0).getId());
                out.setOlderId(statii.get(statii.size() - 1).getId());

                Log.d(Utils.TAG,
                        statii.size() + " mensajes nuevos en " + getTypeText() + " de " + getString("name"));

                long nextId = 1;
                Cursor c = DataFramework.getInstance().getCursor("tweets_user",
                        new String[] { DataFramework.KEY_ID }, null, null, null, null,
                        DataFramework.KEY_ID + " desc", "1");
                if (!c.moveToFirst()) {
                    c.close();
                    nextId = 1;
                } else {
                    long Id = c.getInt(0) + 1;
                    c.close();
                    nextId = Id;
                }

                DataFramework.getInstance().getDB().beginTransaction();

                try {
                    boolean isFirst = true;
                    for (int i = statii.size() - 1; i >= 0; i--) {
                        User u = statii.get(i).getUser();
                        if (u != null) {
                            ContentValues args = new ContentValues();
                            args.put(DataFramework.KEY_ID, "" + nextId);
                            args.put("type_id", tweet_type);
                            args.put("user_tt_id", "" + getId());
                            if (u.getProfileImageURL() != null) {
                                args.put("url_avatar", u.getProfileImageURL().toString());
                            } else {
                                args.put("url_avatar", "");
                            }
                            args.put("username", u.getScreenName());
                            args.put("fullname", u.getName());
                            args.put("user_id", "" + u.getId());
                            args.put("tweet_id", Utils.fillZeros("" + statii.get(i).getId()));
                            args.put("source", statii.get(i).getSource());
                            args.put("to_username", statii.get(i).getInReplyToScreenName());
                            args.put("to_user_id", "" + statii.get(i).getInReplyToUserId());
                            args.put("date", String.valueOf(statii.get(i).getCreatedAt().getTime()));
                            if (statii.get(i).getRetweetedStatus() != null) {
                                args.put("is_retweet", 1);
                                args.put("retweet_url_avatar", statii.get(i).getRetweetedStatus().getUser()
                                        .getProfileImageURL().toString());
                                args.put("retweet_username",
                                        statii.get(i).getRetweetedStatus().getUser().getScreenName());
                                args.put("retweet_source", statii.get(i).getRetweetedStatus().getSource());
                                String t = Utils.getTwitLoger(statii.get(i).getRetweetedStatus());
                                if (t.equals("")) {
                                    args.put("text", statii.get(i).getRetweetedStatus().getText());
                                    args.put("text_urls",
                                            Utils.getTextURLs(statii.get(i).getRetweetedStatus()));
                                } else {
                                    args.put("text", t);
                                }
                                args.put("is_favorite", 0);
                            } else {
                                String t = Utils.getTwitLoger(statii.get(i));
                                if (t.equals("")) {
                                    args.put("text", statii.get(i).getText());
                                    args.put("text_urls", Utils.getTextURLs(statii.get(i)));
                                } else {
                                    args.put("text", t);
                                }

                                if (statii.get(i).isFavorited()) {
                                    args.put("is_favorite", 1);
                                }
                            }

                            if (statii.get(i).getGeoLocation() != null) {
                                args.put("latitude", statii.get(i).getGeoLocation().getLatitude());
                                args.put("longitude", statii.get(i).getGeoLocation().getLongitude());
                            }
                            args.put("reply_tweet_id", statii.get(i).getInReplyToStatusId());

                            if (breakTimeline && isFirst)
                                args.put("has_more_tweets_down", 1);

                            DataFramework.getInstance().getDB().insert("tweets_user", null, args);

                            out.addId(nextId);

                            nextId++;

                            if (isFirst)
                                isFirst = false;
                        }

                    }

                    // finalizar

                    int total = nResult + statii.size();

                    if (total > Utils.MAX_ROW_BYSEARCH && getValueNewCount() < Utils.MAX_ROW_BYSEARCH
                            || total > Utils.MAX_ROW_BYSEARCH_FORCE) {
                        try {
                            Log.d(Utils.TAG, "Limpiando base de datos de " + getTypeText() + " actualmente "
                                    + total + " registros");
                            String date = DataFramework.getInstance()
                                    .getEntityList("tweets_user",
                                            "type_id=" + tweet_type + " and user_tt_id=" + getId(), "date desc")
                                    .get(Utils.MAX_ROW_BYSEARCH).getString("date");
                            String sqldelete = "DELETE FROM tweets_user WHERE type_id=" + tweet_type
                                    + " and user_tt_id=" + getId() + " AND date  < '" + date + "'";
                            DataFramework.getInstance().getDB().execSQL(sqldelete);
                        } catch (OutOfMemoryError e) {
                        }
                    }

                    DataFramework.getInstance().getDB().setTransactionSuccessful();

                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    DataFramework.getInstance().getDB().endTransaction();
                }

            }

        }

        // guardar directs

        if (directs != null) {
            if (directs.size() > 0) {
                out.setNewMessages(directs.size());
                out.setNewerId(directs.get(0).getId());
                out.setOlderId(directs.get(directs.size() - 1).getId());

                Log.d(Utils.TAG, directs.size() + " mensajes directos a " + getString("name"));

                long nextId = 1;
                Cursor c = DataFramework.getInstance().getCursor("tweets_user",
                        new String[] { DataFramework.KEY_ID }, null, null, null, null,
                        DataFramework.KEY_ID + " desc", "1");
                if (!c.moveToFirst()) {
                    c.close();
                    nextId = 1;
                } else {
                    long Id = c.getInt(0) + 1;
                    c.close();
                    nextId = Id;
                }

                DataFramework.getInstance().getDB().beginTransaction();

                try {
                    for (int i = directs.size() - 1; i >= 0; i--) {
                        User u = directs.get(i).getSender();
                        if (u != null) {
                            ContentValues args = new ContentValues();
                            args.put(DataFramework.KEY_ID, "" + nextId);
                            args.put("type_id", tweet_type);
                            args.put("user_tt_id", "" + getId());
                            if (u.getProfileImageURL() != null) {
                                args.put("url_avatar", u.getProfileImageURL().toString());
                            } else {
                                args.put("url_avatar", "");
                            }
                            args.put("username", u.getScreenName());
                            args.put("fullname", u.getName());
                            args.put("user_id", "" + u.getId());
                            args.put("tweet_id", Utils.fillZeros("" + directs.get(i).getId()));
                            args.put("source", "");
                            args.put("to_username", directs.get(i).getRecipientScreenName());
                            args.put("to_user_id", "" + directs.get(i).getRecipientId());
                            args.put("date", String.valueOf(directs.get(i).getCreatedAt().getTime()));
                            args.put("text", directs.get(i).getText());

                            DataFramework.getInstance().getDB().insert("tweets_user", null, args);

                            out.addId(nextId);

                            Log.d(Utils.TAG,
                                    "getRecipientScreenName: " + directs.get(i).getRecipientScreenName());

                            nextId++;
                        }

                    }

                    // finalizar

                    int total = nResult + directs.size();

                    if (total > Utils.MAX_ROW_BYSEARCH && getValueNewCount() < Utils.MAX_ROW_BYSEARCH) {
                        Log.d(Utils.TAG, "Limpiando base de datos de " + getTypeText() + " actualmente " + total
                                + " registros");
                        String date = DataFramework.getInstance()
                                .getEntityList("tweets_user",
                                        "type_id=" + tweet_type + " and user_tt_id=" + getId(), "date desc")
                                .get(Utils.MAX_ROW_BYSEARCH).getString("date");
                        String sqldelete = "DELETE FROM tweets_user WHERE type_id=" + tweet_type
                                + " and user_tt_id=" + getId() + " AND date  < '" + date + "'";
                        DataFramework.getInstance().getDB().execSQL(sqldelete);
                    }

                    DataFramework.getInstance().getDB().setTransactionSuccessful();

                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    DataFramework.getInstance().getDB().endTransaction();
                }

            }

        }
    } catch (TwitterException e) {
        e.printStackTrace();
        RateLimitStatus rate = e.getRateLimitStatus();
        if (rate != null) {
            out.setError(Utils.LIMIT_ERROR);
            out.setRate(rate);
        } else {
            out.setError(Utils.UNKNOWN_ERROR);
        }
    } catch (Exception e) {
        e.printStackTrace();
        out.setError(Utils.UNKNOWN_ERROR);
    }
    return out;
}

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

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    if (CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning
            || !MainActivity.canSwitch) {
        return;//from   w ww.j  av  a  2 s.  c om
    }
    CatchupPull.isRunning = true;

    Log.v("talon_pull", "catchup pull started");

    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    final Context context = getApplicationContext();

    int unreadNow = sharedPrefs.getInt("pull_unread", 0);

    // stop it just in case
    context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH_SERVICE"));

    AppSettings settings = AppSettings.getInstance(context);

    if (settings.liveStreaming) {
        Log.v("talon_pull", "into the try for catchup service");
        Twitter twitter = Utils.getTwitter(context, settings);

        HomeDataSource dataSource = HomeDataSource.getInstance(context);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        List<Status> statuses = new ArrayList<Status>();

        boolean foundStatus = false;

        Paging paging = new Paging(1, 200);

        long[] lastId;
        long id;

        try {
            lastId = dataSource.getLastIds(currentAccount);
            id = lastId[0];
        } catch (Exception e) {
            context.startService(new Intent(context, TalonPullNotificationService.class));
            CatchupPull.isRunning = false;
            return;
        }

        try {
            paging.setSinceId(id);
        } catch (Exception e) {
            paging.setSinceId(1l);
        }

        for (int i = 0; i < settings.maxTweetsRefresh; i++) {
            try {
                if (!foundStatus) {
                    paging.setPage(i + 1);
                    List<Status> list = twitter.getHomeTimeline(paging);

                    statuses.addAll(list);

                    if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) {
                        Log.v("talon_inserting", "found status");
                        foundStatus = true;
                    } else {
                        Log.v("talon_inserting", "haven't found status");
                        foundStatus = false;
                    }

                }
            } catch (Exception e) {
                // the page doesn't exist
                foundStatus = true;
                e.printStackTrace();
            } catch (OutOfMemoryError o) {
                // don't know why...
                o.printStackTrace();
            }
        }

        Log.v("talon_pull", "got statuses, new = " + statuses.size());

        // hash set to remove duplicates I guess
        HashSet hs = new HashSet();
        hs.addAll(statuses);
        statuses.clear();
        statuses.addAll(hs);

        Log.v("talon_inserting", "tweets after hashset: " + statuses.size());

        lastId = dataSource.getLastIds(currentAccount);

        int inserted = dataSource.insertTweets(statuses, currentAccount, lastId);

        if (inserted > 0 && statuses.size() > 0) {
            sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId())
                    .commit();
            unreadNow += statuses.size();
        }

        if (settings.preCacheImages) {
            // delay it 15 seconds so that we can finish checking mentions first
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startService(new Intent(context, PreCacheService.class));
                }
            }, 15000);
        }

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
    }

    try {
        Twitter twitter = Utils.getTwitter(context, settings);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        User user = twitter.verifyCredentials();
        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

        long[] lastId = dataSource.getLastIds(currentAccount);
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId[0] > 0) {
            paging.sinceId(lastId[0]);
        }

        List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging);

        int numNew = dataSource.insertTweets(statuses, currentAccount);

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();

        if (settings.notifications && settings.mentionsNot && numNew > 0) {
            NotificationUtils.refreshNotification(context);
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }

    sharedPrefs.edit().putInt("pull_unread", unreadNow).commit();
    context.startService(new Intent(context, TalonPullNotificationService.class));

    context.sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET"));
    getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null);

    Log.v("talon_pull", "finished with the catchup service");

    CatchupPull.isRunning = false;
}

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

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Context context = getApplicationContext();
    AppSettings settings = AppSettings.getInstance(context);

    // if they have mobile data on and don't want to sync over mobile data
    if (Utils.getConnectionStatus(context) && !settings.syncMobile) {
        return;//www  .  jav a 2 s .c  o  m
    }

    try {
        Twitter twitter = Utils.getTwitter(context, settings);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

        long[] lastId = dataSource.getLastIds(currentAccount);
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId[0] > 0) {
            paging.sinceId(lastId[0]);
        }

        List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging);

        int inserted = MentionsDataSource.getInstance(context).insertTweets(statuses, currentAccount);

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();

        if (settings.notifications && settings.mentionsNot && inserted > 0) {
            if (intent.getBooleanExtra("from_launcher", false)) {
                NotificationUtils.refreshNotification(context, true);
            } else {
                NotificationUtils.refreshNotification(context);
            }
        }

        if (settings.syncSecondMentions) {
            startService(new Intent(context, SecondMentionsRefreshService.class));
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }
}

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

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Context context = getApplicationContext();
    AppSettings settings = AppSettings.getInstance(context);

    // if they have mobile data on and don't want to sync over mobile data
    if (Utils.getConnectionStatus(context) && !settings.syncMobile) {
        return;//from  w w  w .j  a  v a  2 s.c  om
    }

    boolean update = false;
    int numberNew = 0;

    try {
        Twitter twitter = Utils.getSecondTwitter(context);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        if (currentAccount == 1) {
            currentAccount = 2;
        } else {
            currentAccount = 1;
        }

        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

        long lastId = dataSource.getLastIds(currentAccount)[0];
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId > 0) {
            paging.sinceId(lastId);
        }

        List<Status> statuses = twitter.getMentionsTimeline(paging);

        numberNew = MentionsDataSource.getInstance(context).insertTweets(statuses, currentAccount);

        if (numberNew > 0 && settings.notifications && settings.mentionsNot) {
            NotificationUtils.notifySecondMentions(context, currentAccount);
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }
}

From source file:org.wso2.carbon.connector.twitter.TwitterMentionsTimeLine.java

License:Open Source License

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    if (log.isDebugEnabled()) {
        log.info("executing twitter get user time line");
    }/*from  w ww  .j a  va2 s.  c  o  m*/

    try {

        List<Status> results = null;

        String page = (TwitterUtils.lookupTemplateParamater(messageContext, PAGE) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, PAGE).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, PAGE)
                        : "1";

        String count = (TwitterUtils.lookupTemplateParamater(messageContext, COUNT) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, COUNT).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, COUNT)
                        : null;

        String sinceID = (TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID)
                        : null;

        String maxID = (TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID)

                        : null;
        Twitter twitter = new TwitterClientLoader(messageContext).loadApiClient();

        if (page != null && !page.isEmpty()) {
            if (count == null && sinceID == null && maxID == null) {
                results = twitter.getMentionsTimeline(new Paging(Long.parseLong(page)));
            } else if (count != null && sinceID == null && maxID == null) {

                results = twitter
                        .getMentionsTimeline(new Paging(Integer.parseInt(page), Integer.parseInt(count)));
            } else if (count != null && sinceID != null && maxID == null) {
                results = twitter.getMentionsTimeline(
                        new Paging(Integer.parseInt(page), Integer.parseInt(count), Long.parseLong(sinceID)));
            } else {
                results = twitter.getMentionsTimeline(new Paging(Integer.parseInt(page),
                        Integer.parseInt(count), Long.parseLong(sinceID), Long.parseLong(maxID)));
            }
        } else if (page == null && sinceID != null) {
            results = twitter.getMentionsTimeline(new Paging(Integer.parseInt(sinceID)));
        } else {
            results = twitter.getMentionsTimeline();
        }

        OMElement element = this.performSearch(results);

        super.preparePayload(messageContext, element);

    } catch (TwitterException te) {
        log.error("Failed to search twitter : " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    } catch (Exception te) {
        log.error("Failed to search generic: " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    }
}

From source file:twit.Twit.java

public void userMention() throws SQLException, ParseException {
    Twitter twitter = new TwitterFactory().getInstance();
    try {//from w  ww  .jav a 2  s  . co m
        Long since_id = cek_last_mention();
        Paging paging = new Paging().sinceId(since_id);
        List<Status> statuses = twitter.getMentionsTimeline(paging);
        for (twitter4j.Status status : statuses) {
            long ID_TWEET = status.getId();
            String USERNAME = status.getUser().getScreenName();
            String TWEET = status.getText().replace("'", "\\'");
            save_user(USERNAME);
            String ID_MASYARAKAT = cekMasyarakat(USERNAME);
            if (USERNAME.equals("tahupongcode")) { //reply akun sendiri
                save_data_mentions(ID_TWEET);
            } else {
                if (Regex(TWEET)[0].equals("harga")) {
                    //masukkan hasil regex pada array
                    String[] hasil = Regex(TWEET);
                    //ambil isi array
                    int KOMODITAS = cekKomoditas(hasil[2]);
                    String TITIK_DISTRIBUSI = cekTitik(hasil[3]);
                    String HARGA = hasil[4];
                    save_harga(KOMODITAS, TITIK_DISTRIBUSI, ID_MASYARAKAT, USERNAME, HARGA);
                    if (cek_replied(ID_TWEET) == false) {
                        save_data_mentions(ID_TWEET);
                        onStatus(status, 1);
                    }
                } else if (Regex(TWEET)[0].equals("keluhan")) {
                    //masukkan hasil regex pada array
                    String[] hasil = Regex(TWEET);
                    //ambil isi array
                    String SUBJECT = hasil[2];
                    String KELUHAN = hasil[3];
                    String KABUPATEN = cekKabupaten(hasil[4]);
                    insertKeluhan(ID_MASYARAKAT, SUBJECT, KELUHAN, KABUPATEN);
                    if (cek_replied(ID_TWEET) == false) {
                        save_data_mentions(ID_TWEET);
                        onStatus(status, 2);
                    }
                } else {
                    System.out.println("error");
                }
            }
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}