Load next and previous page on ListView Scroll in

2019-07-24 18:30发布

问题:

I am creating a ListView in which I am fetching news from server. And I am getting data page wise i.e. at one time I got one page with 10 items. On down scroll I am hitting that web service again and get next page data to be shown but problem is that suppose I have total 22 items on server and in first attempt I got 22 to 13 then 12 to 3 after that when it comes to last 2 data web service hits again and again. I don't know why web service hit again and again when there is only 2 data. And I don't how to load previous page.

code for the same

       listNews.setOnScrollListener(new AbsListView.OnScrollListener() {

        public void onScrollStateChanged(AbsListView view, int scrollState) {




        }

        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {

            Log.e(TAG, "onScroll: "+firstVisibleItem +" "+visibleItemCount+" "+totalItemCount );
            if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
            {

                callNewsApi((Integer.parseInt(currentPage)+1)+"");
            }
        }
    });

回答1:

You need to validate the last page after each hit response. Better way to do it on server site . But you can also manage it at client end . below is an example .

 private boolean isLastPage;
private int PER_PAGE_COUNT=10;
//@params size- size of data which you get form server each time hit i shoule <= PER_PAGE_COUNT
public void validateLastpage(int size) {
    if(size==0){
        isLastPage=true;
    }else {
        if (size % PER_PAGE_COUNT == 0) {
            isLastPage = false;
        } else {
            isLastPage = true;
        }
    }
}

Now check for isLastPage on each hit. This will stop your extra network called after no more data at server site. Call validateLastpage(int size) after each response with new data size . On each pagination check for last page .

 public void onScroll(AbsListView view, int firstVisibleItem,
                     int visibleItemCount, int totalItemCount) {
    Log.e(TAG, "onScroll: "+firstVisibleItem +" "+visibleItemCount+" "+totalItemCount );
    if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
        if(!isLastPage)
        callNewsApi((Integer.parseInt(currentPage) + 1) + "");
    }
}