2

I'm tring to receive a bitmap image from web and show it on list view's item which contain image view.
But this seems got a trouble in setting image to Bitmap Object "bmImage".
How can i copy received bitmap and return it?

public class DownloadListImageTask extends AsyncTask<String, Integer, Bitmap> {
    Bitmap bmImage;
    public DownloadListImageTask(Bitmap bmImage){
        this.bmImage = bmImage;
    }
    protected Bitmap doInBackground(String... urls){
        String url = urls[0];
        Bitmap bitmap = null;
        try{
            InputStream in = new URL(url).openStream();
            bitmap = BitmapFactory.decodeStream(in);
        }catch(Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }
    protected void onPostExecute(Bitmap result){
        bmImage = result.copy(result.getConfig(), true);
    }
}

following is a useage

Bitmap bitmap;
new DownloadListImageTask(bitmap).execute(url);
adapter.addItem(bitmap);

1 Answers1

2

You create the Bitmap bmImage in your AsyncTask but then you do not return it to the Activity that called the AsyncTask.

One thing you can do is to create a listener in the AsyncTask:

public interface OnBitmapDownloadedListener
{
    void setBitmap(Bitmap bmImage);
}

Implement that in the Activity

public class MyActivity extends AppCompatActivity implements DownloadListImageTask.OnBitmapDownloadListener

Pass that it into the AsyncTask constructor like so:

new DownloadListImageTask(bitmap, this).execute(url)

Then in postExecute() you can call

bmImage = result.copy(result.getConfig(), true);
listener.setBitmap(bmImage)
// Do stuff with the bitmap in setBitmap()
Josh Laird
  • 6,974
  • 7
  • 38
  • 69
  • 1
    http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a would give all answers what he needs i believe. – Inder R Singh Apr 14 '17 at 20:07