List of usage examples for twitter4j Paging Paging
public Paging(int page, long sinceId)
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;/* ww w .ja va2s.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;//from ww w. ja v a2 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 a2s.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 && 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:com.klinker.android.twitter.services.TimelineRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { if (!MainActivity.canSwitch || CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning) { return;/*w w w .ja v a 2 s. com*/ } if (MainActivity.canSwitch) { TimelineRefreshService.isRunning = true; sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); Context context = getApplicationContext(); int numberNew = 0; AppSettings settings = AppSettings.getInstance(context); // if they have mobile data on and don't want to sync over mobile data if (intent.getBooleanExtra("on_start_refresh", false)) { } else 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 = null; long id; try { lastId = dataSource.getLastIds(currentAccount); id = lastId[1]; } catch (Exception e) { try { Thread.sleep(5000); } catch (InterruptedException i) { } TimelineRefreshService.isRunning = false; return; } if (id == 0) { id = 1; } 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; } catch (OutOfMemoryError o) { // don't know why... } } Log.v("talon_pull", "got statuses, new = " + statuses.size()); // hash set to check for 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); Long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime - sharedPrefs.getLong("last_timeline_insert", 0l) < 10000) { Log.v("talon_refresh", "don't insert the tweets on refresh"); sendBroadcast( new Intent("com.klinker.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", 0)); TimelineRefreshService.isRunning = false; return; } else { sharedPrefs.edit().putLong("last_timeline_insert", currentTime).commit(); } 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 (!intent.getBooleanExtra("on_start_refresh", false)) { sharedPrefs.edit().putBoolean("refresh_me", true).commit(); if (settings.notifications && settings.timelineNot && inserted > 0 && !intent.getBooleanExtra("from_launcher", false)) { NotificationUtils.refreshNotification(context); } if (settings.preCacheImages) { startService(new Intent(this, PreCacheService.class)); } } else { Log.v("talon_refresh", "sending broadcast to fragment"); sendBroadcast(new Intent("com.klinker.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", inserted)); } sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); TimelineRefreshService.isRunning = false; } }
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;// ww w . j a va2s.co 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 {//from ww w . jav a2s.c o 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 a va2s .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.mothsoft.integration.twitter.TwitterServiceImpl.java
License:Apache License
@SuppressWarnings("deprecation") public List<Status> getHomeTimeline(AccessToken accessToken, Long sinceId, Short maximumNumber) { final Twitter twitter = this.factory.getInstance(accessToken); final List<Status> statuses = new ArrayList<Status>(maximumNumber); // default maximum number to 200 if null maximumNumber = maximumNumber == null ? 200 : maximumNumber; // default page size to lesser of maximumNumber, 200 final int pageSize = maximumNumber > 200 ? 200 : maximumNumber; int page = 0; while (statuses.size() < maximumNumber) { Paging paging = new Paging(++page, pageSize); final ResponseList temp; if (sinceId != null) { paging = paging.sinceId(sinceId); }//w w w. j ava 2s .co m try { temp = twitter.getHomeTimeline(paging); } catch (TwitterException e) { throw this.wrapException(e); } // break out as soon as we get a page smaller than the designated // page size if (temp.size() == 0) { break; } else { statuses.addAll(temp); } // check rate limit status and warn or skip remaining fetches as // appropriate final RateLimitStatus rateLimitStatus = temp.getRateLimitStatus(); if (rateLimitStatus.getRemaining() < (.1 * rateLimitStatus.getLimit())) { logger.warn("Twitter rate limit approaching. Calls remaining: " + rateLimitStatus.getRemaining()); } if (rateLimitStatus.getRemainingHits() == 0) { final Date resetTime = new Date( System.currentTimeMillis() + (rateLimitStatus.getSecondsUntilReset() * 1000)); logger.error("Twitter rate limit hit. Will reset at: " + resetTime.toLocaleString()); break; } } return statuses; }
From source file:com.mycompany.omnomtweets.RetweetersOfCandidate.java
/** * Method to get the 200 most recent tweets from a candidate. * @return List of 200 most recent tweet ids. */// w w w . j av a 2s . c om public List<String> getCandidateTweetIds() { List<String> candidateTweetIds = new ArrayList<>(); //First try to read in unprocessed tweets List<String> processedIds = new ArrayList<>(); String tempFileName = (candidate.name + "Tweets.txt").replace(" ", ""); File f1 = new File(tempFileName); FileReader fr; try { fr = new FileReader(f1); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { if (line.contains("Processed")) { processedIds.add(line.split(",")[0]); } else { candidateTweetIds.add(line); } } fr.close(); br.close(); } catch (Exception ex) { System.out.println("Something went wrong with file IO"); } //If there weren't any unproccessed ones, get some new ones. if (candidateTweetIds.isEmpty()) { try { List<Status> statuses; Paging paging = new Paging(1, 200); statuses = twitter.getUserTimeline(candidate.account, paging); //System.out.println("Gathered: " + statuses.size() + " tweet ids"); for (Status status : statuses) { candidateTweetIds.add(String.valueOf(status.getId())); } //File to store tweetIds in as an intermediary. FileWriter writeCandidateTweets = new FileWriter(new File(tempFileName), true); for (String tweetId : candidateTweetIds) { writeCandidateTweets.write(tweetId + "\n"); } writeCandidateTweets.close(); } catch (TwitterException te) { System.out.println("Failed to get timeline: " + te.getMessage()); } catch (IOException ex) { Logger.getLogger("FileWriting sucks"); } } return candidateTweetIds; }
From source file:com.soomla.profile.social.twitter.SoomlaTwitter.java
License:Apache License
/** * {@inheritDoc}//from w w w . java2s .c o m */ @Override public void getFeed(Boolean fromStart, final SocialCallbacks.FeedListener feedListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "getFeed"); RefProvider = getProvider(); RefFeedListener = feedListener; preformingAction = ACTION_GET_FEED; try { if (fromStart) { this.lastFeedCursor = 1; } Paging paging = new Paging(this.lastFeedCursor, PAGE_SIZE); twitter.getUserTimeline(paging); } catch (Exception e) { failListener(ACTION_GET_FEED, e.getMessage()); } }