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);
}
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.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 :And the Usage will be like this
The image will be attached automatically when done, for more memory optimization you could use
WeakReference
.Good Luck.