How Do I Get A Bitmap From Asynctask And Set It To My Image
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
Solution 1:
Simply define final ImageView variable linked to the view you want to fill with the Bitmap:
//inside some method e.g. onCreate()
final ImageView imageView = (ImageView) findViewById(R.id.myPrettyImage);
newAsyncTask<String, Void, Bitmap>() {
@OverrideprotectedBitmapdoInBackground(String... params) {
/* here's your code */
}
@OverrideprotectedvoidonPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}.execute(/*your params*/);
Or you can create ImageView field in your AsyncTask extended task:
privateclassExtendedAsyncTaskextendsAsyncTask<String, Void, Bitmap> {
privateImageView[] views;
publicvoidExtendedAsyncTask(ImageView[] views) {
this.views = views;
}
@OverrideprotectedBitmapdoInBackground(String... params) {
/* your code here */
}
@OverrideprotectedvoidonPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
for (ImageViewview: views) {
view.setImageBitmap(bitmap);
}
}
}
and use it:
ExtendedAsyncTaskaTask=newExtendedAsyncTask(newImageView[]{myImageView1, myImageView2, myImageView3});
aTask.execute(/*some params*/);
Solution 2:
This has to be a fairly common task. Why is it so difficult?
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
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
// If you are using normal ImageView
imageLoader.get(Const.URL_IMAGE, newImageListener() {
@Override
publicvoidonErrorResponse(VolleyError error) {
Log.e(TAG, "Image Load Error: " + error.getMessage());
}
@Override
publicvoidonResponse(ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
// load image into imageview
imageView.setImageBitmap(response.getBitmap());
}
}
});
You can read more from here: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Post a Comment for "How Do I Get A Bitmap From Asynctask And Set It To My Image"