7

Why do I get in an AsyncTask which should a android.os.NetworkOnMainThreadException? I thought that an AsyncTask is the solution to that problem. The exxeption is on line 7.

private class ImageDownloadTask extends AsyncTask<String, Integer, byte[]> {
    @Override
    protected byte[] doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                byteBuffer.write(buffer, 0, len);
            }
            return byteBuffer.toByteArray();
        } catch (IOException ex) {
            return new byte[0];
        }
    }
}

I want to use it for downloading a picture.

public byte[] getProfilePicture(Context context, String id) {
    String url = context.getString(R.string.facebook_picture_url_large, id);
    ImageDownloadTask task = new ImageDownloadTask();
    return task.doInBackground(url);
}
Sven Mäurer
  • 715
  • 1
  • 9
  • 19
  • 5
    Add the code where you call the AsyncTask – ianhanniballake Oct 06 '14 at 20:08
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – njzk2 Oct 06 '14 at 20:20
  • No duplicate, because all posts are about ones that have not used a async task but I have and get the exception anyway. – Sven Mäurer Oct 06 '14 at 20:53
  • You need to call .execute() on your AsyncTask in order for it to work in the background. https://developer.android.com/reference/android/os/AsyncTask.html – michaelcarrano Oct 06 '14 at 21:07

2 Answers2

16

By calling doInBackground() directly, you are not actually using the AsyncTask functionality. Instead, you should call execute() and then use the results by overriding the AsyncTask's onPostExecute() method as explained in the Usage section of that same page.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
1

Best way to download an image and attach it to a ImageView is passing the ImageView as the parameter in your async task and set the URL as a tag of the image view then after downloading the task in the OnPostExecute() set the image to the ImageView look at this example :

public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

ImageView imageView = null;

@Override
protected Bitmap doInBackground(ImageView... imageViews) {
    this.imageView = imageViews[0];
    return download_Image((String)imageView.getTag());
}

@Override
protected void onPostExecute(Bitmap result) {
    imageView.setImageBitmap(result);
}


private Bitmap download_Image(String url) {
    ...
}

And the Usage will be like this

ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...someImageUrl ...";

mChart.setTag(URL);
new DownloadImageTask.execute(mChart);

The image will be attached automatically when done, for more memory optimization you could use WeakReference.

Good Luck.

Eefret
  • 4,724
  • 4
  • 30
  • 46