Search code examples
androidandroid-asynctasknetworkonmainthread

android.os.NetworkOnMainThreadException in AsyncTask's doInBackground


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);
}

Solution

  • 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.