android.os.NetworkOnMainThreadException in AsyncTask's doInBackground

筅森魡賤 提交于 2019-11-26 23:30:13

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26224016/android-os-networkonmainthreadexception-in-asynctasks-doinbackground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!