Android ListView dynamically Load more items(from MysqlDatabase) when scroll to the Bottom

894 Views Asked by At

How to detect end of list when scrolling and trigger loading of more data from a WEB request into a ListView

If you are loading data from a WEB server and the list is huge, then the practical solution would be to load a certain amount and if the user scrolls to the end of the list, load some more and keep going until you load the full list

1

There are 1 best solutions below

0
On

You can add paging listener to your ListView: 1. Implement AbsListView.OnScrollListener, for example you can create

abstract class InfiniteListViewPaging

 public abstract class InfiniteListViewPaging implements AbsListView.OnScrollListener {

    private static final String TAG = InfiniteListViewPaging.class.getName();
    public ListView mListView;
    public View mFooterView;
    private boolean mCanLoadMore;
    private boolean mIsLoading;

    /**
     * Should be created before setting the adapter on the {@code listView} as this sets the
     * {@link android.widget.ListView#addFooterView(android.view.View)} on it.
     * @param context
     * @param listView
     */
    public InfiniteListViewPaging(Context context, ListView listView) {
        mFooterView = View.inflate(context, R.layout.footer_list_view, null);
        mListView = listView;
        listView.addFooterView(mFooterView, null, false);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                         int totalItemCount) {
        boolean lessThanOneScreenLeftToScrollDown = (totalItemCount - 2 * visibleItemCount) <= firstVisibleItem;
        if (mCanLoadMore && !mIsLoading && lessThanOneScreenLeftToScrollDown) {
            Log.d(TAG, "Load Next Page!");
            mIsLoading = true;
            loadMore();
        }
    }

    public void setCanLoadMore(boolean canLoadMore) {
        mCanLoadMore = canLoadMore;
        mFooterView.setVisibility(canLoadMore ? View.VISIBLE : View.GONE);
    }

    public abstract void loadMore();

    public void hasFinishedLoading() {
        mIsLoading = false;
    }
  1. And then in your Activity(or Fragment), when initialize ListView set

    mListPaging = new InfiniteListViewPaging(this, getListView()) {
                        @Override
                      public void loadMore() {
                           loadMore();
                       } 
    }; 
    mListView.setOnScrollListener(mListPaging);