Creating AsyncTask in Android
July 14, 2015 6:56 am

Explains how to create an asynctask which allows the image file loading to be done in a background thread.
Part 2 – Addresses the issue with the bitmaps being loaded from the filesystem in the UI thread by creating asynctask in android which in effect creates a background thread to do the file loading.
Steps
Create the AsyncTask Class
public class BitmapWorkerTask extends AsyncTask<File, Void, Bitmap> { WeakReference<ImageView> imageViewReferences; public BitmapWorkerTask(ImageView imageView) { imageViewReferences = new WeakReference<ImageView>(imageView); } @Override protected Bitmap doInBackground(File... params) { return BitmapFactory.decodeFile(params[0].getAbsolutePath()); } @Override protected void onPostExecute(Bitmap bitmap) { if(bitmap != null && imageViewReferences != null) { ImageView viewImage = imageViewReferences.get(); if(viewImage != null) { viewImage.setImageBitmap(bitmap); } } } }
Call the AsyncTask
BitmapWorkerTask workerTask = new BitmapWorkerTask(holder.getImageView()); workerTask.execute(imageFile);
Run the App
Category: Performance