I am trying to use an AsyncTask to convert an image URL to a bitmap in order to set it to an image. I don't understand how to get the bitmap out of the AsyncTask so that I can set it to my the images I am creating in a loop. I also have tried to set the bitmap to the image inside AsyncTask. My understanding is that everything must be done inside AsyncTask but I am unable to reference the images I want to set the value for.
I have researched the URL to bitmap conversion and the AsyncTask but I can't figure out how to combine them to get what I want. This has to be a fairly common task. Why is it so difficult?
How do I reference my images in AsyncTask?
Can I return my bitmap and then set it to the image outside of AsyncTask?
Is there an easier way to set a URL as an image source?
I have included what I have so far.
Thank you for your help and taking the time to read this.
class BitmapTaks extends AsyncTask<String, Void, Bitmap> {
public Bitmap doInBackground(String... urls) {
Bitmap bm = null;
try {
URL aURL = new URL(urls[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("img", "Error getting bitmap", e);
}
return bm;
}
protected void onPostExecute(Bitmap bm) {
//do something after execute
}
}
Simply define final ImageView variable linked to the view you want to fill with the Bitmap:
Or you can create ImageView field in your AsyncTask extended task:
and use it:
I'd really recommend you take a look into the Android Volley library. It's made to abstract away all this AsyncTask boilerplate code. Here's a very nice example of how to set an image bitmap
You can read more from here: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/