Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 234
Sven Mäurer Avatar asked Oct 06 '14 20:10

Sven Mäurer


1 Answers

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.

like image 71
ianhanniballake Avatar answered Nov 16 '22 01:11

ianhanniballake