Android Open Source - campus Bitmap Async Task






From Project

Back to project page campus.

License

The source code is released under:

GNU General Public License

If you think the Android project campus listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package lecho.app.campus.utils;
// w w  w .j a va  2  s  .co m
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

/**
 * Loads bitmap in background and uses it as source for given ImageView.
 * 
 * @author Lecho
 * 
 */
public class BitmapAsyncTask extends AsyncTask<Void, Void, Bitmap> {
  public static final int SYMBOL = 1;
  public static final int PATH = 2;
  private static final String TAG = "BitmapAsyncTask";
  private Context mContext;
  private String mPath;
  private int mRawResource;
  private int mRequestWidth;
  private int mRequestHeight;
  // If false read from raw resources, if true from assets
  private boolean mFromAssets;
  private final WeakReference<ImageView> mImageViewReference;
  private final WeakReference<OnBitmapLoadedListener> mListenerReference;

  public BitmapAsyncTask(Context context, String path, ImageView imageView, int requestWidth, int requestHeight,
      OnBitmapLoadedListener onBitmapLoadedListener) {
    mContext = context;
    mPath = path;
    mFromAssets = true;
    mRequestWidth = requestWidth;
    mRequestHeight = requestHeight;
    // Use a WeakReference to ensure the ImageView can be garbage collected
    mImageViewReference = new WeakReference<ImageView>(imageView);
    // Use a WeakReference in case activity finished before AsyncTask.
    mListenerReference = new WeakReference<BitmapAsyncTask.OnBitmapLoadedListener>(onBitmapLoadedListener);
  }

  public BitmapAsyncTask(Context context, int rawResource, ImageView imageView, int requestWidth, int requestHeight,
      OnBitmapLoadedListener onBitmapLoadedListener) {
    mContext = context;
    mRawResource = rawResource;
    mFromAssets = false;
    mRequestWidth = requestWidth;
    mRequestHeight = requestHeight;
    // Use a WeakReference to ensure the ImageView can be garbage collected
    mImageViewReference = new WeakReference<ImageView>(imageView);
    // Use a WeakReference in case activity finished before AsyncTask.
    mListenerReference = new WeakReference<BitmapAsyncTask.OnBitmapLoadedListener>(onBitmapLoadedListener);
  }

  // Decode image in background.
  @Override
  protected Bitmap doInBackground(Void... params) {
    if (mFromAssets) {
      return decodeSampledBitmapFromAssets(mContext, mPath, mRequestWidth, mRequestHeight);
    } else {
      return decodeSampledBitmapFromRawResource(mContext, mRawResource, mRequestWidth, mRequestHeight);
    }
  }

  // Once complete, see if ImageView is still around and set bitmap.
  @Override
  protected void onPostExecute(Bitmap bitmap) {
    if (mImageViewReference != null && bitmap != null) {
      final ImageView imageView = mImageViewReference.get();
      if (imageView != null) {
        imageView.setImageBitmap(bitmap);
        callListener(true);
        return;
      }
    }
    callListener(false);
  }

  private void callListener(boolean success) {
    if (mListenerReference != null) {
      final OnBitmapLoadedListener listener = mListenerReference.get();
      if (null != listener) {
        listener.onBitmapLoaded(success);
      }

    }
  }

  public static Bitmap decodeSampledBitmapFromAssets(Context context, String path, int reqWidth, int reqHeight) {

    InputStream stream = null;
    try {
      stream = context.getAssets().open(path);
      return decodeSampledBitmap(reqWidth, reqHeight, stream);
    } catch (IOException e) {
      Log.e(TAG, "Could not load place photo from file: " + path, e);
      return null;
    } catch (Exception e) {
      Log.e(TAG, "Could not load place photo from file: " + path, e);
      return null;
    } finally {
      if (null != stream) {
        try {
          stream.close();
        } catch (IOException e) {
          Log.e(TAG, "Could not close stream for place photo from file: " + path, e);
        }
      }
    }

  }

  public static Bitmap decodeSampledBitmapFromRawResource(Context context, int rawResource, int reqWidth,
      int reqHeight) {

    InputStream stream = null;
    try {
      stream = context.getResources().openRawResource(rawResource);

      return decodeSampledBitmap(reqWidth, reqHeight, stream);

    } catch (Exception e) {
      Log.e(TAG, "Could not load place photo from raw resource", e);
      return null;
    } finally {
      if (null != stream) {
        try {
          stream.close();
        } catch (IOException e) {
          Log.e(TAG, "Could not close stream for place photo from raw resource", e);
        }
      }
    }

  }

  private static Bitmap decodeSampledBitmap(int reqWidth, int reqHeight, InputStream stream) {
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, null, options);// File(path, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    if (Config.DEBUG) {
      Log.d(TAG, "Loading image scaled by factor: " + options.inSampleSize);
    }
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(stream, null, options);
  }

  public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

      // Calculate ratios of height and width to requested height and width
      final int heightRatio = Math.round((float) height / (float) reqHeight);
      final int widthRatio = Math.round((float) width / (float) reqWidth);

      // Choose the smallest ratio as inSampleSize value, this will guarantee
      // a final image with both dimensions larger than or equal to the
      // requested height and width.
      inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
  }

  public interface OnBitmapLoadedListener {
    /**
     * Called when AsyncTasc finish loading bitmap and set it as ImageView source. Called only if listener is not
     * null and bitmap was loaded successfully into ImageView.
     */
    public void onBitmapLoaded(boolean success);
  }
}




Java Source Code List

lecho.app.campus.activity.AboutAppActivity.java
lecho.app.campus.activity.CampusMapActivity.java
lecho.app.campus.activity.GalleryActivity.java
lecho.app.campus.activity.LegalInfoActivity.java
lecho.app.campus.activity.PlaceDetailsActivity.java
lecho.app.campus.adapter.GalleryPagesFragmentAdapter.java
lecho.app.campus.adapter.MarkerInfoWindowAdapter.java
lecho.app.campus.adapter.NavigationDrawerAdapter.java
lecho.app.campus.adapter.PlaceDetailsFragmentAdapter.java
lecho.app.campus.adapter.SearchResultViewAdapter.java
lecho.app.campus.adapter.SearchSuggestionAdapter.java
lecho.app.campus.dao.CategoryDao.java
lecho.app.campus.dao.CategoryDao.java
lecho.app.campus.dao.Category.java
lecho.app.campus.dao.Category.java
lecho.app.campus.dao.DaoMaster.java
lecho.app.campus.dao.DaoMaster.java
lecho.app.campus.dao.DaoSession.java
lecho.app.campus.dao.DaoSession.java
lecho.app.campus.dao.FacultyDao.java
lecho.app.campus.dao.FacultyDao.java
lecho.app.campus.dao.Faculty.java
lecho.app.campus.dao.Faculty.java
lecho.app.campus.dao.Main.java
lecho.app.campus.dao.PlaceCategoryDao.java
lecho.app.campus.dao.PlaceCategoryDao.java
lecho.app.campus.dao.PlaceCategory.java
lecho.app.campus.dao.PlaceCategory.java
lecho.app.campus.dao.PlaceDao.java
lecho.app.campus.dao.PlaceDao.java
lecho.app.campus.dao.PlaceFacultyDao.java
lecho.app.campus.dao.PlaceFacultyDao.java
lecho.app.campus.dao.PlaceFaculty.java
lecho.app.campus.dao.PlaceFaculty.java
lecho.app.campus.dao.PlaceUnitDao.java
lecho.app.campus.dao.PlaceUnitDao.java
lecho.app.campus.dao.PlaceUnit.java
lecho.app.campus.dao.PlaceUnit.java
lecho.app.campus.dao.Place.java
lecho.app.campus.dao.Place.java
lecho.app.campus.dao.UnitDao.java
lecho.app.campus.dao.UnitDao.java
lecho.app.campus.dao.Unit.java
lecho.app.campus.dao.Unit.java
lecho.app.campus.fragment.GalleryPageFragment.java
lecho.app.campus.fragment.PlaceDetailsFragment.java
lecho.app.campus.fragment.dialog.NoInternetConnectionDialogFragment.java
lecho.app.campus.fragment.dialog.PlayServicesErrorDialogFragment.java
lecho.app.campus.loader.PlaceDetailsLoader.java
lecho.app.campus.loader.PlacesLoader.java
lecho.app.campus.provider.SearchSuggestionProvider.java
lecho.app.campus.service.PopulateDBIntentService.java
lecho.app.campus.utils.ABSMenuItemConverter.java
lecho.app.campus.utils.BitmapAsyncTask.java
lecho.app.campus.utils.Config.java
lecho.app.campus.utils.DataParser.java
lecho.app.campus.utils.DatabaseHelper.java
lecho.app.campus.utils.ImagesDirAsyncTask.java
lecho.app.campus.utils.NavigationDrawerItem.java
lecho.app.campus.utils.PlaceDetails.java
lecho.app.campus.utils.PlacesList.java
lecho.app.campus.utils.UnitsGroup.java
lecho.app.campus.utils.Utils.java
lecho.app.campus.view.CheckableDrawerItem.java
lecho.app.campus.view.UnitsGroupLayout.java
lecho.app.campus.view.ZoomImageView.java
lecho.app.campus.view.ZoomViewPager.java