Question

I have a OnScrollChangedListener that control if a view become visible to screen, then call an asynctask after remove listener from ScrollView:

scrollView = (ScrollView) findViewById(R.id.scrollView);
scrollListener = new OnScrollChangedListener() {

    @Override
    public void onScrollChanged() {
        Rect scrollBounds = new Rect();
        scrollView.getHitRect(scrollBounds);
        if (spinner.getLocalVisibleRect(scrollBounds)) {
            observer = scrollView.getViewTreeObserver();
            observer.removeOnScrollChangedListener(this);
            new MyTask().execute(null,
                    null, null);
        }
    }
};
observer = scrollView.getViewTreeObserver();
observer.addOnScrollChangedListener(scrollListener);

But i've noticed that something goes wrong. In fact, when i scroll and view becomes visible, if branch is executed twice, so my code call twice the asynctask. Now the task recover some data from internet, and in this way, i obtain duplicated info (and waste of 3g data). How can i do for call task only once, so avoid this behavior?

Was it helpful?

Solution

Boolean isloading = false; //Instance Variable

Make this flag true in onPreExecute() of the async task and false in onPostExecute(). Then before making a new execute request check if this flag is false;

if(!isLoading){
 new MyTask().execute(null,null, null);

OTHER TIPS

scrollListener = new OnScrollChangedListener() {

    AsyncTask<?, ?, ?> myTask;

    @Override
    public void onScrollChanged() {
        Rect scrollBounds = new Rect();
        if (spinner.getLocalVisibleRect(scrollBounds)) {
            synchronized (this) {
                if (myTask == null) {
                    observer = scrollView.getViewTreeObserver();
                    observer.removeOnScrollChangedListener(this);
                    myTask = new MyTask().execute(null, null, null);
                }
            }
        }
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top