Samarth Agarwal
Samarth Agarwal

Reputation: 2134

ListView onScroll being called multiple times

I know that this question has been asked before but I think I am really close to my solution and therefore I wish to do this way. I am using a ListView and populating it with some data. Now, I am trying to populate it with some more data when the user reaches the bottom. This should continue as long as there are less than 100 items in the ListView. But the code below add all the data at once when I scroll it to the bottom for the first time. I guess there are tens of calls to my async method that loads more data.

@Override
                    public void onScroll(AbsListView absListView, int firstVisibleItem,
                                         int visibleItemCount, int totalItemCount) {
                        scrollTask myscrolltask = new scrollTask();
                        int lastVisibleIndex = absListView.getLastVisiblePosition();

                        if(lastVisibleIndex != totalItemCount - 1)
                        {
                            System.out.print("lastVisibleIndex "+lastVisibleIndex);
                            System.out.print("totalItemCount-1 " + (totalItemCount-1));
                            myscrolltask.cancel(true);
                            return;
                        }
                        if(moreNewsAvailable == 0)
                            return;
                        if(totalItemCount > 75)
                            return;


                        Log.v("Total Item Count", String.valueOf(totalItemCount));
                        int lastItem = firstVisibleItem + visibleItemCount;
                        if(lastItem == totalItemCount && totalItemCount<=75 && moreNewsAvailable==1 && lastVisibleIndex != -1 && totalItemCount!=0)  //Means that you have reached the bottom
                        {
                            Log.v("LastVisibleItemPosition", String.valueOf(lastVisibleIndex));

                            setProgressBarIndeterminateVisibility(true);

                            myscrolltask.execute("");
                        }
                    }

Is there anyway around? How can I make sure that only one call to the async is made when reaching bottom?

Upvotes: 2

Views: 2362

Answers (1)

Gopal Singh Sirvi
Gopal Singh Sirvi

Reputation: 4649

create a Boolean variable and set that variable to true in task execution and again set that Boolean to true on task completion. Check if task is in progress than dont execute on scroll method.

if(!isLoading){
        if(lastVisibleIndex != totalItemCount - 1)
        {
            System.out.print("lastVisibleIndex "+lastVisibleIndex);
            System.out.print("totalItemCount-1 " + (totalItemCount-1));
            myscrolltask.cancel(true);
            return;
        }
        if(moreNewsAvailable == 0)
            return;
        if(totalItemCount > 75)
            return;
        }

Upvotes: 1

Related Questions