List of usage examples for twitter4j Paging Paging
public Paging(int page, long sinceId)
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;/*from w w w . j a v a 2 s . co 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 ww w . jav a 2s . 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.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;// ww w . jav a 2 s . 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.daiv.android.twitter.services.TimelineRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { if (!MainActivity.canSwitch || CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning) { return;// ww w.j a v a 2 s. c o m } if (MainActivity.canSwitch) { TimelineRefreshService.isRunning = true; sharedPrefs = getSharedPreferences("com.daiv.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("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; } catch (OutOfMemoryError o) { // don't know why... } } Log.v("Test_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("Test_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("Test_refresh", "don't insert the tweets on refresh"); sendBroadcast(new Intent("com.daiv.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", 0)); TimelineRefreshService.isRunning = false; context.getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); 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 || settings.favoriteUserNotifications) && inserted > 0 && !intent.getBooleanExtra("from_launcher", false)) { NotificationUtils.refreshNotification(context, !settings.timelineNot); } if (settings.preCacheImages) { startService(new Intent(this, PreCacheService.class)); } } else { Log.v("Test_refresh", "sending broadcast to fragment"); sendBroadcast( new Intent("com.daiv.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", inserted)); } sendBroadcast(new Intent("com.daiv.android.Test.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); TimelineRefreshService.isRunning = false; } }
From source file:com.daiv.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;/* w ww.j ava 2s .co m*/ } WidgetRefreshService.isRunning = true; sharedPrefs = getSharedPreferences("com.daiv.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("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; } catch (OutOfMemoryError o) { // don't know why... } } 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 = 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.daiv.android.Test.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.daiv.android.twitter.ui.main_fragments.other_fragments.ListFragment.java
License:Apache License
public int doRefresh() { int numberNew = 0; try {/*from www . jav a 2s .c o m*/ twitter = Utils.getTwitter(context, DrawerActivity.settings); 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 (Exception e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); e.printStackTrace(); } return 0; }
From source file:com.discord.discordbot.eventhandlers.TweetMe.java
private void onTrump(MessageReceivedEvent event) { Paging paging = new Paging(1, 10); try {//from www . j a v a2 s.co m statuses = (ArrayList<Status>) unauthenticatedTwitter.getUserTimeline("google", paging); log.info("ArrayList created size: " + statuses.size()); printMessage(event, statuses.toString()); } catch (TwitterException e) { log.warn("Error could not intitate twitter onTrump"); System.err.println(e.getMessage() + "\n" + e.getStackTrace()); } }
From source file:com.eventattend.portal.bl.TwitterBL.java
License:Open Source License
public List tweets(Twitter twitter, String screenName, TwitterDTO twitterDTO) throws BaseAppException { List tweetList = new ArrayList(); List<Status> statuses = null; Paging paging = new Paging(1, 10); try {//w w w . java2s . co m statuses = twitter.getUserTimeline(screenName, paging); } catch (TwitterException e) { processTwitterException(e); } int i = 1; if (!statuses.isEmpty()) { for (Status status : statuses) { if (i <= 10) { User user = status.getUser(); twitterDTO = new TwitterDTO(); // // if(userId==status.getUser().getId()){ if (status.getId() != 0) { System.out.println(i + "TweetId=> " + status.getId()); twitterDTO.setTweetId(String.valueOf(status.getId())); } if (user.getProfileImageURL() != null) { twitterDTO.setUserImg(user.getProfileImageURL().toString()); } if (user.getScreenName() != null) { twitterDTO.setUserScreeName("http://twitter.com/" + user.getScreenName()); } if (user.getName() != null) { twitterDTO.setUserName(user.getName()); } if (status.getText() != null) { twitterDTO.setTweet(status.getText()); } System.out.println(status.getId() + " : " + status.getCreatedAt() + " >> " + status.getText()); tweetList.add(twitterDTO); i++; } else { break; } } } return tweetList; }
From source file:com.javielinux.database.EntityTweetUser.java
License:Apache License
public InfoSaveTweets saveTweets(Context context, Twitter twitter) { InfoSaveTweets out = new InfoSaveTweets(); try {//w ww . jav a 2 s . c om 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.activities.main_fragments.home_fragments.HomeFragment.java
License:Apache License
public int doRefresh() { int numberNew = 0; if (TimelineRefreshService.isRunning || WidgetRefreshService.isRunning || CatchupPull.isRunning) { // quit if it is running in the background return 0; }/* w w w . j av a 2s.co m*/ try { Cursor cursor = cursorAdapter.getCursor(); if (cursor.moveToLast()) { long id = cursor.getLong(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_TWEET_ID)); sharedPrefs.edit().putLong("current_position_" + currentAccount, id).commit(); HomeDataSource.getInstance(context).markPosition(currentAccount, id); //HomeContentProvider.updateCurrent(currentAccount, context, id); } } catch (Exception e) { } boolean needClose = false; context.sendBroadcast(new Intent("com.klinker.android.twitter.CLEAR_PULL_UNREAD")); twitter = Utils.getTwitter(context, settings); final List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); long[] lastId = null; long id; try { lastId = HomeDataSource.getInstance(context).getLastIds(currentAccount); id = lastId[1]; } catch (Exception e) { id = sharedPrefs.getLong("account_" + currentAccount + "_lastid", 1l); } Log.v("talon_inserting", "since_id=" + id); try { paging.setSinceId(id); } catch (Exception e) { // 0 for some reason, so dont set one and let the database sort which should show and which shouldn't } long beforeDownload = Calendar.getInstance().getTimeInMillis(); 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 (TwitterException e) { Log.v("talon_error", "code: " + e.getErrorCode()); if (e.getErrorCode() == 88) { // rate limit reached rateLimited = true; foundStatus = true; return 0; } } catch (Exception e) { // the page doesn't exist e.printStackTrace(); Log.v("talon_error", "error with refresh"); foundStatus = true; } catch (OutOfMemoryError o) { // don't know why... } } long afterDownload = Calendar.getInstance().getTimeInMillis(); Log.v("talon_inserting", "downloaded " + statuses.size() + " tweets in " + (afterDownload - beforeDownload)); if (statuses.size() > 0) { statuses.remove(statuses.size() - 1); } HashSet hs = new HashSet(); hs.addAll(statuses); statuses.clear(); statuses.addAll(hs); Log.v("talon_inserting", "tweets after hashset: " + statuses.size()); manualRefresh = false; if (needClose) { HomeDataSource.dataSource = null; Log.v("talon_home_frag", "sending the reset home broadcase in needclose section"); dontGetCursor = true; context.sendBroadcast(new Intent("com.klinker.android.twitter.RESET_HOME")); } if (lastId == null) { try { lastId = HomeDataSource.getInstance(context).getLastIds(currentAccount); } catch (Exception e) { // let the lastId = new long[] { 0, 0, 0, 0, 0 }; } } try { numberNew = insertTweets(statuses, lastId); } catch (NullPointerException e) { return 0; } if (numberNew > statuses.size()) { numberNew = statuses.size(); } if (numberNew > 0 && statuses.size() > 0) { sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()).commit(); } Log.v("talon_inserting", "inserted " + numberNew + " tweets in " + (Calendar.getInstance().getTimeInMillis() - afterDownload)); //numberNew = statuses.size(); unread = numberNew; statuses.clear(); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); long now = new Date().getTime(); long alarm = now + settings.timelineRefresh; PendingIntent pendingIntent = PendingIntent.getService(context, HOME_REFRESH_ID, new Intent(context, TimelineRefreshService.class), 0); if (settings.timelineRefresh != 0) am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.timelineRefresh, pendingIntent); else am.cancel(pendingIntent); int unreadCount; try { unreadCount = HomeDataSource.getInstance(context).getUnreadCount(currentAccount); } catch (Exception e) { unreadCount = numberNew; } return unreadCount; }