Search in sources :

Example 1 with Paging

use of twitter4j.Paging in project twicalico by moko256.

the class BaseTweetListFragment method onCreateView.

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = super.onCreateView(inflater, container, savedInstanceState);
    int dp8 = Math.round(8f * getResources().getDisplayMetrics().density);
    getRecyclerView().setPadding(dp8, 0, 0, 0);
    getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.right = dp8;
            outRect.top = dp8;
        }
    });
    if (getActivity() instanceof GetRecyclerViewPool) {
        getRecyclerView().setRecycledViewPool(((GetRecyclerViewPool) getActivity()).getTweetListViewPool());
    }
    adapter = new StatusesAdapter(getContext(), list);
    adapter.setOnLoadMoreClick(position -> subscription.add(getResponseSingle(new Paging().maxId(list.get(position - 1) - 1L).sinceId(list.get(list.size() >= position + 2 ? position + 2 : position + 1)).count(GlobalApplication.statusLimit)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(result -> {
        if (result.size() > 0) {
            list.remove(position);
            statusIdsDatabase.deleteIds(ArrayUtils.convertToLongList(-1L));
            adapter.notifyItemRemoved(position);
            List<Long> ids = Observable.from(result).map(Status::getId).toList().toSingle().toBlocking().value();
            if (ids.get(ids.size() - 1).equals(list.get(position))) {
                ids.remove(ids.size() - 1);
            } else {
                ids.add(-1L);
            }
            list.addAll(position, ids);
            statusIdsDatabase.insertIds(position, ids);
            adapter.notifyItemRangeInserted(position, ids.size());
        } else {
            list.remove(position);
            statusIdsDatabase.deleteIds(ArrayUtils.convertToLongList(-1L));
            adapter.notifyItemRemoved(position);
        }
    }, e -> {
        e.printStackTrace();
        Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE).setAction(R.string.retry, v -> onLoadMoreList()).show();
    })));
    setAdapter(adapter);
    if (!isInitializedList()) {
        adapter.notifyDataSetChanged();
    }
    LAST_SAVED_LIST_POSITION = statusIdsDatabase.getListViewPosition();
    getRecyclerView().getLayoutManager().scrollToPosition(LAST_SAVED_LIST_POSITION);
    return view;
}
Also used : Status(twitter4j.Status) Context(android.content.Context) Rect(android.graphics.Rect) Arrays(java.util.Arrays) Bundle(android.os.Bundle) WindowManager(android.view.WindowManager) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) NonNull(android.support.annotation.NonNull) TwitterStringUtils(com.github.moko256.twicalico.text.TwitterStringUtils) ArrayList(java.util.ArrayList) Observable(rx.Observable) CachedIdListSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedIdListSQLiteOpenHelper) Single(rx.Single) Toast(android.widget.Toast) Schedulers(rx.schedulers.Schedulers) Display(android.view.Display) View(android.view.View) TwitterException(twitter4j.TwitterException) ResponseList(twitter4j.ResponseList) StaggeredGridLayoutManager(android.support.v7.widget.StaggeredGridLayoutManager) LayoutInflater(android.view.LayoutInflater) Point(android.graphics.Point) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) ViewGroup(android.view.ViewGroup) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) Gravity(android.view.Gravity) List(java.util.List) TypedValue(android.util.TypedValue) Status(twitter4j.Status) Paging(twitter4j.Paging) Snackbar(android.support.design.widget.Snackbar) ArrayUtils(com.github.moko256.twicalico.array.ArrayUtils) Rect(android.graphics.Rect) Paging(twitter4j.Paging) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) Point(android.graphics.Point) RecyclerView(android.support.v7.widget.RecyclerView)

Example 2 with Paging

use of twitter4j.Paging in project Talon-for-Twitter by klinker24.

the class HomeFragment method doRefresh.

public int doRefresh() {
    int numberNew = 0;
    if (TimelineRefreshService.isRunning || WidgetRefreshService.isRunning || CatchupPull.isRunning) {
        // quit if it is running in the background
        return 0;
    }
    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;
}
Also used : Status(twitter4j.Status) TimelineRefreshService(com.klinker.android.twitter.services.TimelineRefreshService) Paging(twitter4j.Paging) ArrayList(java.util.ArrayList) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Cursor(android.database.Cursor) TwitterException(twitter4j.TwitterException) StaleDataException(android.database.StaleDataException) Date(java.util.Date) AlarmManager(android.app.AlarmManager) PendingIntent(android.app.PendingIntent) TwitterException(twitter4j.TwitterException) HashSet(java.util.HashSet)

Example 3 with Paging

use of twitter4j.Paging in project Talon-for-Twitter by klinker24.

the class FavoriteTweetsFragment method doRefresh.

public int doRefresh() {
    int numberNew = 0;
    try {
        twitter = Utils.getTwitter(context, DrawerActivity.settings);
        long[] lastId = FavoriteTweetsDataSource.getInstance(context).getLastIds(currentAccount);
        final List<Status> statuses = new ArrayList<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.getFavorites(settings.myScreenName, paging);
                    statuses.addAll(list);
                }
            } catch (Exception e) {
                // the page doesn't exist
                foundStatus = true;
            } catch (OutOfMemoryError o) {
            // don't know why...
            }
        }
        manualRefresh = false;
        FavoriteTweetsDataSource dataSource = FavoriteTweetsDataSource.getInstance(context);
        numberNew = dataSource.insertTweets(statuses, currentAccount, lastId);
        return numberNew;
    } catch (Exception e) {
        // Error in updating status
        e.printStackTrace();
    }
    return 0;
}
Also used : Status(twitter4j.Status) FavoriteTweetsDataSource(com.klinker.android.twitter.data.sq_lite.FavoriteTweetsDataSource) Paging(twitter4j.Paging) ArrayList(java.util.ArrayList)

Example 4 with Paging

use of twitter4j.Paging in project Talon-for-Twitter by klinker24.

the class MentionsRefreshService method onHandleIntent.

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", 0);
    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;
    }
    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());
    }
}
Also used : Context(android.content.Context) AppSettings(com.klinker.android.twitter.settings.AppSettings) Paging(twitter4j.Paging) Twitter(twitter4j.Twitter) Intent(android.content.Intent) MentionsDataSource(com.klinker.android.twitter.data.sq_lite.MentionsDataSource) TwitterException(twitter4j.TwitterException)

Example 5 with Paging

use of twitter4j.Paging in project twicalico by moko256.

the class BaseTweetListFragment method onInitializeList.

@Override
protected void onInitializeList() {
    setRefreshing(true);
    subscription.add(getResponseSingle(new Paging(1, 20)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(result -> {
        List<Long> ids = Observable.from(result).map(Status::getId).toList().toSingle().toBlocking().value();
        list.addAll(ids);
        statusIdsDatabase.addIds(ids);
        adapter.notifyDataSetChanged();
        setRefreshing(false);
    }, e -> {
        e.printStackTrace();
        Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE).setAction(R.string.retry, v -> {
            setRefreshing(true);
            onInitializeList();
        }).show();
        setRefreshing(false);
    }));
}
Also used : Context(android.content.Context) Rect(android.graphics.Rect) Arrays(java.util.Arrays) Bundle(android.os.Bundle) WindowManager(android.view.WindowManager) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) NonNull(android.support.annotation.NonNull) TwitterStringUtils(com.github.moko256.twicalico.text.TwitterStringUtils) ArrayList(java.util.ArrayList) Observable(rx.Observable) CachedIdListSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedIdListSQLiteOpenHelper) Single(rx.Single) Toast(android.widget.Toast) Schedulers(rx.schedulers.Schedulers) Display(android.view.Display) View(android.view.View) TwitterException(twitter4j.TwitterException) ResponseList(twitter4j.ResponseList) StaggeredGridLayoutManager(android.support.v7.widget.StaggeredGridLayoutManager) LayoutInflater(android.view.LayoutInflater) Point(android.graphics.Point) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) ViewGroup(android.view.ViewGroup) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) Gravity(android.view.Gravity) List(java.util.List) TypedValue(android.util.TypedValue) Status(twitter4j.Status) Paging(twitter4j.Paging) Snackbar(android.support.design.widget.Snackbar) ArrayUtils(com.github.moko256.twicalico.array.ArrayUtils) Paging(twitter4j.Paging) ArrayList(java.util.ArrayList) ResponseList(twitter4j.ResponseList) List(java.util.List)

Aggregations

Paging (twitter4j.Paging)13 ArrayList (java.util.ArrayList)10 Status (twitter4j.Status)10 Context (android.content.Context)9 TwitterException (twitter4j.TwitterException)9 Intent (android.content.Intent)8 AppSettings (com.klinker.android.twitter.settings.AppSettings)6 Twitter (twitter4j.Twitter)5 HashSet (java.util.HashSet)4 List (java.util.List)4 Point (android.graphics.Point)3 Rect (android.graphics.Rect)3 Bundle (android.os.Bundle)3 NonNull (android.support.annotation.NonNull)3 Snackbar (android.support.design.widget.Snackbar)3 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)3 RecyclerView (android.support.v7.widget.RecyclerView)3 StaggeredGridLayoutManager (android.support.v7.widget.StaggeredGridLayoutManager)3 TypedValue (android.util.TypedValue)3 Display (android.view.Display)3