Android.os.NetworkOnMainThreadException in AsyncTask doInBackground

Why am I getting in AsyncTask, which should be android.os.NetworkOnMainThreadException? I thought the AsyncTask solution was the solution to this problem. 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 to upload an image.

 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); } 
+6
source share
2 answers

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

+14
source

The best way to upload an image and attach it to ImageView is to pass ImageView as a parameter in your async task and set the URL as the image tag, and then after loading the task in OnPostExecute() set the image to 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 use will be that way

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

The image will be automatically added after completion, for better memory optimization you can use WeakReference .

Good luck.

+1
source

Source: https://habr.com/ru/post/976322/


All Articles