Android: Calling Asynctask.execute() Crashes The App
I have an activity where I load an image from the given URI. The android training article suggested that it should be done in background so that it does not block the UI. I followe
Solution 1:
Instead of passing ImaageView reference to Async class standard practice try to define custom interface for load bitmap
publicinterfaceImageBitampLoadListener {
publicvoidonBitampLoad(Bitmap bitmap);
}
Pass custom interface reference Async :
private ImageBitmapLoadListener listener;
publicImageLoaderTask(ImageBitmapLoadListener listener){
this.listener = listener;
}
Set call back from Async :
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(listener!=null){
listener.onBitampLoad(bitmap);
}
}
Set custom listener to Async and get Bitamp :
ImageLoaderTasktask=newImageLoaderTask(newImageBitmapLoadListener() {
@OverridepublicvoidonBitampLoad(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
});
task.execute(uri);
Solution 2:
I solved the issue by overriding onProgressUpdate() method of the AsyncTask. Now my ImageLoader code looks like
@OverrideprotectedvoidonProgressUpdate(Void... values) {
try {
if (imageViewReference != null && bitmap != null) {
finalImageViewimageView= imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Throwable t) {
Utils.showErrorDialog(ChatWindow.getInstance(), t);
}
}
@OverrideprotectedvoidonPostExecute(Bitmap bitmap) {
this.bitmap = bitmap;
onProgressUpdate();
}
Post a Comment for "Android: Calling Asynctask.execute() Crashes The App"