Example usage for twitter4j Paging setSinceId

List of usage examples for twitter4j Paging setSinceId

Introduction

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

Prototype

public void setSinceId(long sinceId) 

Source Link

Usage

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

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    // it is refreshing elsewhere, so don't start
    if (WidgetRefreshService.isRunning || TimelineRefreshService.isRunning || CatchupPull.isRunning
            || !MainActivity.canSwitch) {
        return;//from  www  .jav a  2s. c o m
    }
    WidgetRefreshService.isRunning = true;
    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_icon)
            .setTicker(getResources().getString(R.string.refreshing) + "...")
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.refreshing_widget) + "...")
            .setProgress(100, 100, true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.drawer_sync_dark));

    NotificationManager mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(6, mBuilder.build());

    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;
    }

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

    HomeDataSource dataSource = HomeDataSource.getInstance(context);

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

    List<twitter4j.Status> statuses = new ArrayList<twitter4j.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) {
        WidgetRefreshService.isRunning = false;
        return;
    }

    paging.setSinceId(id);

    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;
        } catch (OutOfMemoryError o) {
            // don't know why...
        }
    }

    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 = HomeDataSource.getInstance(context).insertTweets(statuses, currentAccount, lastId);

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

    if (settings.preCacheImages) {
        startService(new Intent(this, PreCacheService.class));
    }

    context.sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET"));
    getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null);
    sharedPrefs.edit().putBoolean("refresh_me", true).commit();

    mNotificationManager.cancel(6);

    WidgetRefreshService.isRunning = false;
}

From source file:com.klinker.android.twitter.ui.main_fragments.other_fragments.ListFragment.java

License:Apache License

public int doRefresh() {
    int numberNew = 0;

    try {//ww w.  j ava  2 s .co  m

        twitter = Utils.getTwitter(context, DrawerActivity.settings);

        User user = twitter.verifyCredentials();
        long[] lastId = ListDataSource.getInstance(context).getLastIds(listId);

        final List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>();

        boolean foundStatus = false;

        Paging paging = new Paging(1, 200);

        if (lastId[0] > 0) {
            paging.setSinceId(lastId[0]);
        }

        for (int i = 0; i < DrawerActivity.settings.maxTweetsRefresh; i++) {

            try {
                if (!foundStatus) {
                    paging.setPage(i + 1);
                    List<Status> list = twitter.getUserListStatuses(listId, paging);

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

        manualRefresh = false;

        ListDataSource dataSource = ListDataSource.getInstance(context);
        numberNew = dataSource.insertTweets(statuses, listId);

        return numberNew;

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

    return 0;
}

From source file:com.klinker.android.twitter.ui.main_fragments.other_fragments.MentionsFragment.java

License:Apache License

@Override
public void onRefreshStarted() {
    new AsyncTask<Void, Void, Cursor>() {

        private boolean update;
        private int numberNew;

        @Override/*from   w ww .j ava  2s.  c o  m*/
        protected void onPreExecute() {
            DrawerActivity.canSwitch = false;
        }

        @Override
        protected Cursor doInBackground(Void... params) {
            try {
                twitter = Utils.getTwitter(context, DrawerActivity.settings);

                long[] lastId = MentionsDataSource.getInstance(context).getLastIds(currentAccount);

                Paging paging;
                paging = new Paging(1, 200);
                if (lastId[0] > 0) {
                    paging.setSinceId(lastId[0]);
                }

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

                if (statuses.size() != 0) {
                    update = true;
                    numberNew = statuses.size();
                } else {
                    update = false;
                    numberNew = 0;
                }

                MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

                try {
                    dataSource.markAllRead(settings.currentAccount);
                } catch (Throwable e) {

                }

                numberNew = dataSource.insertTweets(statuses, currentAccount);
                unread = numberNew;

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

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            long now = new Date().getTime();
            long alarm = now + DrawerActivity.settings.mentionsRefresh;

            PendingIntent pendingIntent = PendingIntent.getService(context, MENTIONS_REFRESH_ID,
                    new Intent(context, MentionsRefreshService.class), 0);

            if (DrawerActivity.settings.mentionsRefresh != 0)
                am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, DrawerActivity.settings.mentionsRefresh,
                        pendingIntent);
            else
                am.cancel(pendingIntent);

            if (DrawerActivity.settings.syncSecondMentions) {
                // refresh the second account
                context.startService(new Intent(context, SecondMentionsRefreshService.class));
            }

            return MentionsDataSource.getInstance(context).getCursor(sharedPrefs.getInt("current_account", 1));
        }

        @Override
        protected void onPostExecute(Cursor cursor) {

            Cursor c = null;
            try {
                c = cursorAdapter.getCursor();
            } catch (Exception e) {

            }

            cursorAdapter = new TimeLineCursorAdapter(context, cursor, false);
            attachCursor();

            try {
                if (update) {
                    CharSequence text = numberNew == 1
                            ? numberNew + " " + getResources().getString(R.string.new_mention)
                            : numberNew + " " + getResources().getString(R.string.new_mentions);
                    showToastBar(text + "", jumpToTop, 400, true, toTopListener);
                    int size = mActionBarSize
                            + (DrawerActivity.translucent ? DrawerActivity.statusBarHeight : 0);
                    try {
                        listView.setSelectionFromTop(numberNew + listView.getHeaderViewsCount()
                                - (getResources().getBoolean(R.bool.isTablet) ? 1 : 0)
                                - (settings.jumpingWorkaround ? 1 : 0), size);
                    } catch (Exception e) {
                        // not attached
                    }
                } else {
                    CharSequence text = getResources().getString(R.string.no_new_mentions);
                    showToastBar(text + "", allRead, 400, true, toTopListener);
                }
            } catch (Exception e) {
                // user closed the app before it was done
            }

            refreshLayout.setRefreshing(false);

            DrawerActivity.canSwitch = true;

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

            }
        }
    }.execute();
}

From source file:com.marpies.ane.twitter.functions.GetDirectMessagesFunction.java

License:Apache License

private Paging getPaging(int count, long sinceID, long maxID) {
    Paging paging = null;
    if (count != 20) {
        paging = new Paging();
        paging.setCount(count);//from ww w  . j  a v  a2 s.  co  m
    }
    if (sinceID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setSinceId(sinceID);
    }
    if (maxID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setMaxId(maxID);
    }
    return paging;
}

From source file:com.marpies.ane.twitter.functions.GetSentDirectMessagesFunction.java

License:Apache License

private Paging getPaging(int count, long sinceID, long maxID, int page) {
    Paging paging = null;
    if (count != 20) {
        paging = new Paging();
        paging.setCount(count);/*from  ww w .  j a va 2  s  . c  o  m*/
    }
    if (sinceID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setSinceId(sinceID);
    }
    if (maxID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setMaxId(maxID);
    }
    if (page > 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setPage(page);
    }
    return paging;
}

From source file:de.vanita5.twittnuker.loader.support.Twitter4JStatusesLoader.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  www. j  ava  2 s.c  o  m*/
public final List<ParcelableStatus> loadInBackground() {
    final File serializationFile = getSerializationFile();
    final List<ParcelableStatus> data = getData();
    if (isFirstLoad() && getTabPosition() >= 0 && serializationFile != null) {
        final List<ParcelableStatus> cached = getCachedData(serializationFile);
        if (cached != null) {
            data.addAll(cached);
            Collections.sort(data);
            return new CopyOnWriteArrayList<>(data);
        }
    }
    final List<Status> statuses;
    final boolean truncated;
    final Context context = getContext();
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int loadItemLimit = prefs.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT);
    try {
        final Paging paging = new Paging();
        paging.setCount(loadItemLimit);
        if (mMaxId > 0) {
            paging.setMaxId(mMaxId);
        }
        if (mSinceId > 0) {
            paging.setSinceId(mSinceId - 1);
        }
        statuses = new ArrayList<>();
        truncated = truncateStatuses(getStatuses(getTwitter(), paging), statuses, mSinceId);
    } catch (final TwitterException e) {
        // mHandler.post(new ShowErrorRunnable(e));
        e.printStackTrace();
        return new CopyOnWriteArrayList<>(data);
    }
    final long minStatusId = statuses.isEmpty() ? -1 : Collections.min(statuses).getId();
    final boolean insertGap = minStatusId > 0 && statuses.size() > 1 && !data.isEmpty() && !truncated;
    mHandler.post(CacheUsersStatusesTask.getRunnable(context, new StatusListResponse(mAccountId, statuses)));
    for (final Status status : statuses) {
        final long id = status.getId();
        final boolean deleted = deleteStatus(data, id);
        data.add(new ParcelableStatus(status, mAccountId, minStatusId == id && insertGap && !deleted));
    }
    Collections.sort(data);
    final ParcelableStatus[] array = data.toArray(new ParcelableStatus[data.size()]);
    for (int i = 0, size = array.length; i < size; i++) {
        final ParcelableStatus status = array[i];
        if (shouldFilterStatus(mDatabase, status) && !status.is_gap && i != size - 1) {
            deleteStatus(data, status.id);
        }
    }
    saveCachedData(serializationFile, data);
    return new CopyOnWriteArrayList<>(data);
}

From source file:it.greenvulcano.gvesb.social.twitter.directcall.TwitterOperationGetUserTimeline.java

License:Open Source License

@Override
public void execute(SocialAdapterAccount account) throws SocialAdapterException {
    try {/*from  w w w .  ja v a 2  s . c  om*/
        Twitter twitter = (Twitter) account.getProxyObject();
        Paging paging = new Paging();
        if ((sinceId != null) && !"".equals(sinceId)) {
            paging.setSinceId(Long.parseLong(sinceId));
        }
        if ((maxId != null) && !"".equals(maxId)) {
            paging.setMaxId(Long.parseLong(maxId));
        }
        if ((count != null) && !"".equals(count)) {
            paging.setCount(Integer.parseInt(count));
        }
        if ((userId == null) || "".equals(userId)) {
            dataUser = twitter.getScreenName();
            dataUserId = String.valueOf(twitter.getId());
            statusList = twitter.getUserTimeline(paging);
        } else {
            User user = null;
            try {
                long id = Long.parseLong(userId);
                user = twitter.showUser(id);
                statusList = twitter.getUserTimeline(id, paging);
            } catch (NumberFormatException exc) {
                user = twitter.showUser(userId);
                statusList = twitter.getUserTimeline(userId, paging);
            }
            dataUser = user.getScreenName();
            dataUserId = String.valueOf(user.getId());
        }
    } catch (NumberFormatException exc) {
        logger.error("Call to TwitterOperationGetUserTimeline failed. Check userId[" + userId + "], sinceId["
                + sinceId + "], maxId[" + maxId + "] and count[" + count + "] format.", exc);
        throw new SocialAdapterException("Call to TwitterOperationGetUserTimeline failed. Check followingId["
                + userId + "], sinceId[" + sinceId + "], maxId[" + maxId + "] and count[" + count + "] format.",
                exc);
    } catch (TwitterException exc) {
        logger.error("Call to TwitterOperationGetUserTimeline followingId[" + userId + "], sinceId[" + sinceId
                + "], maxId[" + maxId + "] and count[" + count + "] failed.", exc);
        throw new SocialAdapterException("Call to TwitterOperationGetUserTimeline followingId[" + userId
                + "], sinceId[" + sinceId + "], maxId[" + maxId + "] and count[" + count + "] failed.", exc);
    }
}

From source file:net.lacolaco.smileessence.view.dialog.UserDetailDialogFragment.java

License:Open Source License

@Override
public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
    final MainActivity activity = (MainActivity) getActivity();
    final Account currentAccount = activity.getCurrentAccount();
    Twitter twitter = TwitterApi.getTwitter(currentAccount);
    final StatusListAdapter adapter = getListAdapter(activity);
    Paging paging = TwitterUtils.getPaging(TwitterUtils.getPagingCount(activity));
    if (adapter.getCount() > 0) {
        paging.setSinceId(adapter.getTopID());
    }/*from   ww w.  j ava2s . c o m*/
    new UserTimelineTask(twitter, getUserID(), paging) {
        @Override
        protected void onPostExecute(twitter4j.Status[] statuses) {
            super.onPostExecute(statuses);
            for (int i = statuses.length - 1; i >= 0; i--) {
                twitter4j.Status status = statuses[i];
                adapter.addToTop(new StatusViewModel(status, currentAccount));
            }
            updateListView(refreshView.getRefreshableView(), adapter, true);
            refreshView.onRefreshComplete();
        }
    }.execute();
}

From source file:net.lacolaco.smileessence.view.HomeFragment.java

License:Open Source License

@Override
public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
    final MainActivity activity = (MainActivity) getActivity();
    if (activity.isStreaming()) {
        new UIHandler() {
            @Override/*w  ww  .j a  va 2s  .c om*/
            public void run() {
                StatusListAdapter adapter = getListAdapter(activity);
                updateListViewWithNotice(refreshView.getRefreshableView(), adapter, true);
                refreshView.onRefreshComplete();
            }
        }.post();
        return;
    }
    final Account currentAccount = activity.getCurrentAccount();
    Twitter twitter = TwitterApi.getTwitter(currentAccount);
    final StatusListAdapter adapter = getListAdapter(activity);
    Paging paging = TwitterUtils.getPaging(TwitterUtils.getPagingCount(activity));
    if (adapter.getCount() > 0) {
        paging.setSinceId(adapter.getTopID());
    }
    new HomeTimelineTask(twitter, activity, paging) {
        @Override
        protected void onPostExecute(twitter4j.Status[] statuses) {
            super.onPostExecute(statuses);
            for (int i = statuses.length - 1; i >= 0; i--) {
                twitter4j.Status status = statuses[i];
                StatusViewModel viewModel = new StatusViewModel(status, currentAccount);
                adapter.addToTop(viewModel);
                StatusFilter.filter(activity, viewModel);
            }
            updateListViewWithNotice(refreshView.getRefreshableView(), adapter, true);
            refreshView.onRefreshComplete();
        }
    }.execute();
}

From source file:net.lacolaco.smileessence.view.MentionsFragment.java

License:Open Source License

@Override
public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
    final MainActivity activity = (MainActivity) getActivity();
    final Account currentAccount = activity.getCurrentAccount();
    Twitter twitter = TwitterApi.getTwitter(currentAccount);
    final StatusListAdapter adapter = getListAdapter(activity);
    Paging paging = TwitterUtils.getPaging(TwitterUtils.getPagingCount(activity));
    if (adapter.getCount() > 0) {
        paging.setSinceId(adapter.getTopID());
    }//  w  w  w  . java2  s.c  om
    new MentionsTimelineTask(twitter, activity, paging) {
        @Override
        protected void onPostExecute(twitter4j.Status[] statuses) {
            super.onPostExecute(statuses);
            for (int i = statuses.length - 1; i >= 0; i--) {
                twitter4j.Status status = statuses[i];
                adapter.addToTop(new StatusViewModel(status, currentAccount));
            }
            updateListViewWithNotice(refreshView.getRefreshableView(), adapter, true);
            refreshView.onRefreshComplete();
        }
    }.execute();
}