Example usage for twitter4j Paging setPage

List of usage examples for twitter4j Paging setPage

Introduction

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

Prototype

public void setPage(int page) 

Source Link

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 ww . j  a  va  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.TimelineRefreshService.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    if (!MainActivity.canSwitch || CatchupPull.isRunning || WidgetRefreshService.isRunning
            || TimelineRefreshService.isRunning) {
        return;//from  w w w  .  jav a 2  s . co  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;//from  ww  w  . ja va2s .c  o  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 {// www  .  j  a v  a2  s  . 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.ikungolf.java.javatwitter.directmessage.GetSentDirectMessages.java

License:Apache License

/**
 * Usage: java twitter4j.examples.directmessages.GetSentDirectMessages
 *
 * @param args message/*from   w  w w . j  ava 2  s  . c  om*/
 */
public static void main(String[] args) {
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        Paging page = new Paging(1);
        List<DirectMessage> directMessages;
        do {
            directMessages = twitter.getSentDirectMessages(page);
            for (DirectMessage message : directMessages) {
                System.out.println("To: @" + message.getRecipientScreenName() + " id:" + message.getId() + " - "
                        + message.getText());
            }
            page.setPage(page.getPage() + 1);
        } while (directMessages.size() > 0 && page.getPage() < 10);
        System.out.println("done.");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get sent messages: " + te.getMessage());
        System.exit(-1);
    }
}

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;
    }/*from   ww  w. j a  v  a2  s  .  com*/

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

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  ww  w .j a  v a  2s  .  co m
    }
    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.TimelineRefreshService.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    if (!MainActivity.canSwitch || CatchupPull.isRunning || WidgetRefreshService.isRunning
            || TimelineRefreshService.isRunning) {
        return;//from   w  w  w. ja  v  a  2  s  .  c  om
    }
    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;/*from   ww  w . ja v a 2s.  c om*/
    }
    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  w  w  w .j a va  2  s .c  om

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