KDeogharkar
KDeogharkar

Reputation: 10959

Handle AsyncTask in Class

I am using AsyncTask Class to handle images that are coming from the server to display it in the ImageView
I have one Next button in my code to call the next image using following code:

private class LoadImage extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPostExecute(Void result) {

        if (imgque != null) {
            imgSelectedQue.setImageDrawable(imgque);
            if (getActivity() != null) {
                adjustResourceEnvelope();
            }
        }

    }

    @Override
    protected void onPreExecute() {
        imgque = null;
        imgSelectedQue.setImageDrawable(null);
        imgSelectedQue.requestLayout();
    }

    @SuppressWarnings("deprecation")
    @Override
    protected Void doInBackground(Void... params) {
        InputStream is;
        try {
            is = (InputStream) new URL(Constants.PLAYER_SERVICE_BASE_URL + "/playerservice"
                    + imageurl).getContent();
            imgque = Drawable.createFromStream(is, null);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            imgque = null;
            e.printStackTrace();
        }

        return null;

    }
}

Now the issue is that if I click the next button REPEATEDLY then it call the AsyncTask that many times and ImageView displaying all the images like "Slide-Show" because all the url images are in queue.
Is there any way to display only last AsyncTask call image?

Upvotes: 1

Views: 166

Answers (2)

KDeogharkar
KDeogharkar

Reputation: 10959

I Found the Solution for this.
If anyone facing the same issue.
I Added new lines

if (loadimage != null)
 {
   loadimage.cancel(true);
   loadimage = null;
}

loadimage.cancel(true) will stop the AsyncTask if it is already Running

then execute the AsycTask()

loadimage = new LoadImage();
loadimage.execute();

In this way i am able to call only last AsyncTask that what I required.

Upvotes: 0

Pratik Sharma
Pratik Sharma

Reputation: 13405

Do something like this:

[1] When you call LoadImage AsyncTask on click of NEXT button disable NEXT button.

[2] On onPreExecute() method of your LoadImage AsyncTask enable your NEXT button again.

OR,

You can achieve such things with use of simple FLAG also. By setting it as true and false.

Hope this helps you.

Thanks.

Upvotes: 1

Related Questions