Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when ListView has reached the bottom - onScroll() or onScrollStateChanged()?

This seems a question with many answers already; however, I can't find a common approach to this. I'm trying to add data to a ListView when the bottom is reached; data are retrieved from Internet using an AsyncTask. ListView already has an adapter attached to it.

So, searching for a good way to accomplish this, I arrived at two different approaches.

  1. The first one, the onScrollStateChanged() approach, is basically related to this page. However, it use parameters that don't have correspondence in the actual API. At the same time, this link use the right API, but I don't know if in the right way. I tried with the first of the two links, but it's kind of meh. Debugging the app, diff values vary a lot and I don't know how to correctly interpet the expression. Also, I don't know how to fix an offset from which I can start to retrieving data; I mean, I'd like to execute code not when I'm about to reach the bottom, but just before I reach it. Also, sometimes it get called even if we scroll to the top.
  2. The second one is the onScroll() approach, that is used in this answer or, in a different way, in this code. I tried adapting the last of the two codes, but it cause many problems and the data are loaded even if we don't reach the bottom of the list.

So, what approach is best? When and why should I prefer one or the other? Which of the two should I use in my case?

like image 954
tigerjack Avatar asked Jan 27 '15 18:01

tigerjack


1 Answers

Here's some code for my suggested third approach, which I use in my own projects. I use the adapter's getView method to detect when the end of the list has been reached.

public View getView(int position, View convertView, ViewGroup parent) {
    // handle recycling/creating/initializing view
    if(reachedEndOfList(position)) loadMoreData();
    return convertView;
}

private boolean reachedEndOfList(int position) {
    // can check if close or exactly at the end
    return position == getSize() - 1;
}

private void loadMoreData() {
    // Perhaps set flag to indicate you're loading and check flag before proceeding with AsyncTask or whatever
}
like image 104
darnmason Avatar answered Sep 24 '22 23:09

darnmason