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
public interface ImageBitampLoadListener {
public void onBitampLoad(Bitmap bitmap);
}
Pass custom interface reference Async :
private ImageBitmapLoadListener listener;
public ImageLoaderTask(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 :
ImageLoaderTask task = new ImageLoaderTask(new ImageBitmapLoadListener() {
@Override
public void onBitampLoad(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
@Override
protected void onProgressUpdate(Void... values) {
try {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Throwable t) {
Utils.showErrorDialog(ChatWindow.getInstance(), t);
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
this.bitmap = bitmap;
onProgressUpdate();
}
Post a Comment for "Android: Calling AsyncTask.execute() Crashes The App"